0

Why in c# can't we wrap anonymous objects in list of objects? For Example I have seen this Question in StackOverFlow C# Linq, object definition does not contains a property

var anynomousObject = new { Amount = 10, weight = 20 };

List<object> ListOfAnynomous = new List<object> { anynomousObject, anynomousObject };
var productQuery =
            from prod in ListOfAnynomous
            select new { prod.Amount, prod.weight };

foreach (var v in productQuery)
{
    Console.WriteLine(v.Amount);
    Console.WriteLine(v.weight);
}

and the answer was that he should wrap the anonymous in list of dynamic but actually I can't understand why in the run time we can't get their values.

1
  • how exactly you wrapped the anonymous in list of dynamic? I've just made a simple test and looks like from dynamic prod in ... works. Commented Aug 9, 2015 at 9:27

1 Answer 1

2

Anonymous types are also types and they're compiled into actual classes. That is, anonymous doesn't mean untyped.

If you add anonymous type instances to a List<object> you're upcasting them to object and you lose the typing itself, thus, you can't access anonymous type instance properties.

Instead of storing them in a List<dynamic>, you should go with other solution: store in a generic list of anonymous type. Since you don't gain access to anonymous type names (it's anonymous, they've no name - well, they compile into actual classes, but this is how internally works at compile/run time, it's a low-level detail), you can't use explicit typing, but C# has type-inferred variables:

// compiles to string a = "hello"; assignment defines the type
var a = "hello"; 

...so, what about this?

// Use a type-inferred array to define the items and then convert the array
// to list!
// Now you can use each anonymous type instance properties in LINQ ;)
var listOfAnonymousInstances = new [] { new { Amount = 10, weight = 20 } }.ToList();
// If you mouse over the var keyword, you'll find that it's a List<a`>!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.