gdoron
gdoron

Reputation: 150253

Strongly typed collection Implicit and explicit cast

public void Foo (IEnumerable<object> objects)
{
}

var strings = new List<string>{"first", "second", "third"};
Foo(strings); // Compilation Error.
Foo(strings.Cast<object>()); // O.k.
  1. Why the first call to Foo doesn't compile? string derived from object.
  2. If I can cast the list to object and it's compiled, why the compiler doesn't do it by his own?

Upvotes: 1

Views: 780

Answers (3)

Tudor
Tudor

Reputation: 62439

  1. Generics are strict in the sense that you cannot assign a collection of a derived type to a collection of a supertype. You must provide the exact type used to instantiate the collection.
  2. Because it cannot know what you want to do. Same reason why the following line does not compile:

    string s = new object();
    

To force an "unsafe" type cast on the user would be too much liberty given to the compiler.

Upvotes: 0

Rikard Pavelic
Rikard Pavelic

Reputation: 496

You wan't to look up co-variance and contra-variance.

It's new feature in .NET 4.0

Upvotes: 0

Oded
Oded

Reputation: 499002

The first call compiles in .NET 4.0.

In previous versions, the generic types have to match exactly.

I suggest reading the blogs posts of Eric Lippert regarding variance (covariance and contravariance).

Upvotes: 4

Related Questions