Why can't I do this with implicit types in C#?
Asked Answered
K

2

6
var x = new { a = "foobar", b = 42 };
List<x.GetType()> y;

Is there a different way to do what I want to do here?

If there's not, I don't really see all that much point in implicit types...

Kirkwood answered 15/10, 2009 at 6:8 Comment(2)
You can do it, but it takes reflection. I can't remember the exact code off the top of my head, but I'm sure someone will post something soon.Blumenthal
If you need to know the type of an object, why would you create it anonymously? You use them when type doesn't matter or need to be known.Erlin
F
11

x.GetType() is a method call, evaluated at execution time. It therefore can't be used for a compile-time concept like the type of a variable. I agree that occasionally it would be quite handy to be able to do something similar (specifying the compile-time type of a variable as a type argument elsewhere), but currently you can't. I can't say I regularly miss it though.

However, you can do:

var x = new { a = "foobar", b = 42 };
var y = new[] { x };
var z = y.ToList();

You could also write a simple extension method to create a list generically:

public static List<T> InList<T>(this T item)
{
    return new List<T> { item };
}

(Pick a different name if you want :)

Then:

var x = new { a = "foobar", b = 42 };
var y = x.InList();

As Marc shows, it doesn't actually have to be an extension method at all. The only important thing is that the compiler can use type inference to work out the type parameter for the method so that you don't have to try to name the anonymous type.

Implicitly typed local variables are useful for a variety of reasons, but they're particularly useful in LINQ so that you can create an ad-hoc projection without creating a whole new type explicitly.

Farmhand answered 15/10, 2009 at 6:15 Comment(1)
Ahhh. Thanks for the explanation, and the InList() code snippet was what I was looking for. Thanks again!Kirkwood
D
6

There are ways of doing this with a generic 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...

Depressive answered 15/10, 2009 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.