tags:

views:

85

answers:

4

Considering the following setup, how can I restrain IConnection to only contain IPort of the same ConnectionType in Ports? Maybe I am overlooking something obvious here:

Enum ConnectionType
{
    Undefined,
    Type1,
    Type2
}


IConnection
{
    ConnectionType ConnectionType {get;set}
    IEnumerable<IPort> Ports {get;set;}
}

IPort
{
    ConnectionType ConnectionType {get;set;}
}
+3  A: 

You cannot enforce such constraints at compile time.

You will have to do some checking at runtime.

leppie
+2  A: 

In order to control the type of IPorts, you will need to change the class to not expose the list in a writeable manner.

Make the property read-only, returning a new ReadOnlyCollection to prevent adding any type of IPort to the internal collection. Add an AddPort method that will only allow adding an IPort of the right type.

Oded
Actually I am doing that already in a way, the code in the question is just a dummy to show the problem. I was just thinking, if it would be possible to force the type check into the interface.
Residuum
A: 

Instead of having the connection type in the IPort interface, have a property of IConnection, e.g.

IConnection
{
  ConnectionType ConnectionType { get; }
  IEnumerable<IPort> Ports { get; }
}

IPort
{
  IConnection Connection { get; }
}

Management of these properties should be left to the implementation.

Matthew Abbott
Would that simply create a similar problem. Making sure that the connection pointed to by all ports is the connection the port belongs to?
Rune FS
I guess, but it does enforce that the ConnectionType that the IPort instance can connect to is the same ConnectionType that the IConnection interface is set to.
Matthew Abbott
+1  A: 

How about wrapping up the enum and using generics?

    public interface IConnectionType
{
    ConnectionTypeEnum Connection{ get; set;}
}

public enum ConnectionTypeEnum
{
   Undefined,
   Type1,
   Type2
}

public interface IPort<T> where T : IConnectionType
{
}

public interface IConnection<T> where T : IConnectionType
{
    IEnumerable<IPort<T>> Ports {get;set;}
}

I'm not sure if there's any point in having the enum anymore though

Jonny Cundall
While this is a viable answer for the simple example in my question, it will not work, if I try to put further restrains in the interface.
Residuum