Why can't I do this with implicit types in C #?
var x = new { a = "foobar", b = 42 }; List<x.GetType()> y; Is there any other way to do what I want to do here?
If itβs not, I donβt see anything in it in implicit types ...
x.GetType() is a method call evaluated at runtime. Therefore, it cannot be used for a compile-time concept such as a variable type. I agree that sometimes it would be very convenient to have something like this (indicating the type of compilation time of the variable as an argument of the type elsewhere), but at the moment you cannot. I canβt say that I miss him regularly.
However, you can do:
var x = new { a = "foobar", b = 42 }; var y = new[] { x }; var z = y.ToList(); You can also write a simple extension method to create a list as a whole:
public static List<T> InList<T>(this T item) { return new List<T> { item }; } (Choose a different name if you want :)
Then:
var x = new { a = "foobar", b = 42 }; var y = x.InList(); As Mark shows, in fact, this should not be an extension method at all. The only important thing is that the compiler can use type inference to determine the type parameter for the method, so you do not need to try to name an anonymous type.
Implicitly typed local variables are useful for a number of reasons, but they are especially useful in LINQ, so you can create an advertising projection without explicitly creating a completely new type.
There are ways to do this using the general method:
public static List<T> CreateList<T>(T example) { return new List<T>(); } ... var list = CreateList(x); or by creating a list with data and then emptying it ...