InvisiblePanda
InvisiblePanda

Reputation: 1609

Implicit conversion from IEnumerable<int> to IEnumerable<dynamic>

I haven't used dynamic much in C# so far, so I came across a (small) problem when trying to create a simple WebGrid-like component for learning purposes.

The normal WebGrid takes as its data source an IEnumerable<dynamic>, so I emulated that. Then I created a view like the following:

@model IEnumerable<int>

@{
  MyWebGrid grid = new MyWebGrid(Model);
}

In the MVC project, this leads to a runtime conversion error, so I created a small console application (this doesn't compile of course):

class Program
{
  class Foo { public int Id { get; } }

  static void Main()
  {
    CheckConversion(new List<int>().AsEnumerable()); // Error

    CheckConversion(new List<Foo>()); // works

    int x = 5;
    CheckSingleParameterConversion(x); // works
  }

  private static void CheckConversion(IEnumerable<dynamic> source) { }
  private static void CheckSingleParameterConversion(dynamic val) { }
}

The error (in short): Cannot convert from IEnumerable<int> to IEnumerable<dynamic>.

What is the exact reasoning behind these differing behaviors? I know that dynamic is a reference type and could thus understand why there might be some problem with the IEnumerable<int> here, but why does it work in the single parameter case then?

Upvotes: 2

Views: 458

Answers (1)

Uladz
Uladz

Reputation: 1968

Problem is not in dynamic itself, it's all about variance.

As said in MSDN

Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.

So IEnumerable<int> cannot be casted to IEnumerable<dynamic>, because int is a value type and dynamic is just an object marked with special attribute.

Upvotes: 3

Related Questions