1
\$\begingroup\$

I have a some classes and interface

public interface IGeoObject
 {
 GeoCoordinate GetGeocoordinate();
 }
public class User : IGeoObject
 {
 public GeoCoordinate GetGeocoordinate()
 {
 //...
 return GeoCoordinate; 
 }
 } 
public class Venue : IGeoObject
 { 
 public GeoCoordinate GetGeocoordinate()
 {
 //...
 return GeoCoordinate;
 }
 }
public class Place : IGeoObject
 { 
 public GeoCoordinate GetGeocoordinate()
 {
 //...
 return GeoCoordinate;
 }
 }

I have, example variable users with type List<User>

And I have method with signature

double GetMinDistance(List<IGeoObject> objects, GeoCoordinate position)

I can't pass users to GetMinDistance, because covariance of generic types not work.

I can create additional list and use method .ConvertAll (or .CasT<T>):

List<IGeoObject> list = new List<User>(listUser).ConvertAll(x => (IGeoObject)x);
var dist = GeoTest.GetMinDistance(list, position);

I'm not sure that this is the most elegant solution. Most embarrassing that the caller must do this conversion.

This is similar to my problems in the architecture? There are more elegant solutions?

P.S. Long story, but I really can not give the coordinates of the same species in all classes.

svick
24.5k4 gold badges53 silver badges89 bronze badges
asked Oct 21, 2013 at 23:13
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

Covariance works only when it's safe and only on interfaces (and delegates, but that's not relevant here). So, if you wanted to take advantage of it, you would have to declare GetMinDistance() like this:

double GetMinDistance(IEnumerable<IGeoObject> objects, GeoCoordinate position)

Instead of IEnumerable, you could use IReadOnlyList if you're on .Net 4.5.

answered Oct 22, 2013 at 1:01
\$\endgroup\$
5
\$\begingroup\$

You can make GetMinDistance generic:

double GetMinDistance<T>(IList<T> objects, GeoCoordinate position)
 where T: IGeoObject
{ 
 // ...
}

You can use it like this:

List<User> user = ....;
GetMinDistance(user, position);
answered Oct 21, 2013 at 23:47
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.