Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting from IEnumerable<Object> to IEnumerable<string>

Recently I found a very surprising behavior in c#. I had a method which takes IEnumerable<Object> as a parameter and i was passing IEnumerable<string> but it's not possible. While in c# everything can be upcast to Object than why this is not possible? It's totally confusing for me. Please someone clear me on this issue.

like image 721
Embedd_0913 Avatar asked Mar 04 '09 07:03

Embedd_0913


3 Answers

The technical term for this is that generics are invariant in C# 3.0 and earlier. From C#4.0 onward, the cast works.

What invariant means is that there is no relationship between two generic types just because their generic type parameters are related (i.e. are sub- or supertypes of each other).

In your example, there is no typing relationship between an IEnumerable<object> and an IEnumerable<string>, just because string is a subtype of object. They're just considered two completely unrelated types, like a string and an int (they still both are subtypes of object, but everything is)

There are a few workarounds and exceptions for this issue you've run into.

First, you can cast each string individually to object, if you're using .NET 3.0 you can do that using the Cast<T>() extension method. Otherwise, you can use a foreach and put the result into a new variable of the static type you want.

Second, arrays are an exception for reference type, i.e. passing in a string[] type to a method acccepting object[] types should work.

like image 133
Kurt Schelfthout Avatar answered Sep 22 '22 17:09

Kurt Schelfthout


As others have pointed out, generics types are invariant. IEnumerable<T> could be co-variant but C# doesn't currently support specifying variants. C# 4.0 is expected to support variants so this might be supported in the future.

To work around this now you can using a the LINQ extension method Cast<object>(). Assuming you have a method called Foo that takes an IEnumerable<object>>. You can call it like this,

Foo(stringEnumerable.Cast<object>());
like image 28
chuckj Avatar answered Sep 24 '22 17:09

chuckj


The easiest way to pass IEnumerable<string> to function requiring IEnumerable<object> is through converting function like this:

public IEnumerable<object> convert<T>(IEnumerable<T> enumerable)
    {
    foreach (T o in enumerable)
        yield return o;
    }

When C# 4 comes out, this won't be neccessary, because it will support covariance and contravariance.

like image 34
Juozas Kontvainis Avatar answered Sep 25 '22 17:09

Juozas Kontvainis