Let's say that I have the following generic class:
public class Control<TItem>
{
public Control(TItem item)
{
}
}
When I try to pass an object of anonymous type to the constructor, the compilation fails:
var objectOfAnonymousType = new { Foo = "bar" };
// cannot compile:
var control1 = new Control(objectOfAnonymousType);
However if I do this not through the constructor, but through a generic method outside the class, it seems to work:
// can compile:
var control2 = CreateControl(objectOfAnonymousType);
Factory method used:
static Control<TItem> CreateControl<TItem>(TItem item)
{
return new Control<TItem>(item);
}
I cannot understand the reasoning behind this limitation. Anybody can explain?