List GetContactInfo() {
List list = new List();
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(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.