Working with C# Anonymous Types
You can't return a list of an anonymous type, it will have to be a list of object
. Thus you will lose the type information.
Option 1
Don't use an anonymous type. If you are trying to use an anonymous type in more than one method, then create a real class.
Option 2
Don't downcast your anonymous type to object
. (must be in one method)
var list = allContacts
.Select(c => new { c.ContactID, c.FullName })
.ToList();
foreach (var o in list) {
Console.WriteLine(o.ContactID);
}
Option 3
Use the dynamic keyword. (.NET 4 required)
foreach (dynamic o in list) {
Console.WriteLine(o.ContactID);
}
Option 4
Use some dirty reflection.
foreach ( var o in list ) {
Console.WriteLine( o.ContactID );
}
this will work only if list is IEnumerable<anonymous type>
, like this:
var list = allContacts.Select(c => new {
ContactID = c.ContactID,
FullName = c.FullName
});
}
but you can't return anonymous types, because you must define return type (you can't return var
) and anonymous types can't have names. you should create non-anonymous type if you with to pass it. Actually anonymous types should not be used too much, except for inside of queries.
If you have a method like this:
List<object> GetContactInfo() {
List<object> list = new List<object>();
foreach ( Contact c in allContacts ) {
list.Add( new {
ContactID = c.ContactID,
FullName = c.FullName
});
}
return list;
}
You shouldn't really do this, but there's a very ugly and not future-proof technique that you can use:
static T CastByExample<T>(object target, T example) {
return (T)target;
}
// .....
var example = new { ContactID = 0, FullName = "" };
foreach (var o in GetContactInfo()) {
var c = CastByExample(o, example);
Console.WriteLine(c.ContactID);
}
It relies on the fact (which can change!) that the compiler reuses anonymous types for types that have the same "shape" (properties names and types). Since your "example" matches the "shape" of the type in the method, the same type is reused.
Dynamic variables in C# 4 are the best way to solve this though.