Mark
Mark

Reputation: 71

How to pass "Dictionary<x,Class>" as Dictionary<x,Interface>"?

New to both C# and Stackoverflow...please feel free to indicate if this should be asked differently or elsewhere.

Given:

public interface IPoint {...}
public struct DeliveryPoint : IPoint {...}

and code that generated a dictionary with a large number of delivery points:

...
Dictionary<uint,DeliveryPoint> dict = new Dictionary<uint,DeliveryPoint>();
...

The points now need to be passed to a routine which requires the interface type:

public void doSomething( Dictionary<uint,IPoint> dict ) { ...}

Thought I'd be able to do something like:

doSomething( dict );

Only solution I've found is to create a new List and copy all of the points which seems to defeat the whole purpose of having implemented the interface in the first place.

Is there a better approach?

Upvotes: 2

Views: 176

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134841

Make the method generic over the values where the type implements the interface.

public void DoSomething<TPoint>(IDictionary<uint, TPoint> dict) where TPoint : IPoint
{
    // do stuff
}

Upvotes: 3

Related Questions