0

I am trying to pass a List to a constructer which takes List.

Constructor

public Constructor (List<IData> data) { ... }

Calling Constructor

var a = new Constructor (new List<source> ()); This is failed

source is subclass of IData where IData is an interface.

If I passing it like that, I will get the exception.

But if I cast it like this : var a = (new List<string>()).Cast<object>(), it become messy. Later, if I want to use string functions, I will need to cast the object back to string before I can call the string function.

LittleFunny
  • 8,155
  • 15
  • 87
  • 198
  • 3
    Change your constructor to be `IEnumerable data` - and you will be able to pass in a `List` – Rob Jun 22 '16 at 04:50
  • How does it work. Why the other way not working – LittleFunny Jun 22 '16 at 04:58
  • I lost the Count property when using IEnumerable. I need to use it on my xamarin android inside the PagerAdapter class. – LittleFunny Jun 22 '16 at 05:03
  • Because `IEnumerable` is defined as being covariant. In short: It also makes a contract that you can never add to an `IEnumerable`, you can only read from it. Therefore, it's safe to allow `IEnumerable` to be cast to `IEnumerable` where `A : B`. `List` is *not* covariant, and you can add to the collection, so you cannot do that. – Rob Jun 22 '16 at 05:03
  • Good to understand.. In my scenario may not be the right way though – LittleFunny Jun 22 '16 at 05:05
  • 1
    See also this post: Put a lion into a zoo of giraffes http://stackoverflow.com/questions/2033912/c-sharp-variance-problem-assigning-listderived-as-listbase – MakePeaceGreatAgain Jun 22 '16 at 05:06
  • 2
    @Simon You can still use `Count()` rather than `Count`. I can't off the top of my head think of an interface that `List` implements which is covariant and exposes `Count`. So, if `Count()` is too expensive for your use case, you may need to create your own covariant interface and implement a custom collection – Rob Jun 22 '16 at 05:11
  • Ok that is system.Linq.Enumerable not System.Collection. Does System.Linq.IEnumerable Count function an expensive to use .... – LittleFunny Jun 22 '16 at 05:17
  • @Simon It's not necessarily expensive, no. It depends on your use-case. Does your list have billions of elements? Then it might be an issue. You'll need to investigate yourself whether or not it's a bottle neck. It's unlikely to be a bottleneck, but I figured I'd mention it, as it *is* more expensive than the `Count` property. – Rob Jun 22 '16 at 05:44
  • Probably not many data in each of the list ... – LittleFunny Jun 22 '16 at 05:47
  • I assume if you use the generic interface within your methods signature and pass an instance of `List` (as in your example) to it the `Count()`-method will simply call the property `Count` making it an O(1)-operation. No need to iterate whole collection. – MakePeaceGreatAgain Jun 22 '16 at 06:00

0 Answers0