❔ can't access anonymous object properties by name
in this https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/anonymous-types
the first example shows them instanciating new object v with amount and message properties
then they just type v.amount to access it
but in my code i do this and pass a list of generated anonymous objects to an other class and then i cant access the properties by name anymore
help
Anonymous Types
Anonymous types in C# encapsulate a set of read-only properties in an object without having to explicitly define a type. The compiler generates a name.
10 Replies
Because you're converting the anonymous objects to
object
Which is not the sameok I just changed object to dynamic and seems to work
Probably not the proper way to do it, but that will at least verify the issue
what is the proper way without creating a class ?
create a class
hehe ok
Anonymous types only work in their current scope. If you need to pass it around it needs to be a real type or you have to use dynamic.
Or you have to pass the anonymous type as a type parameter
But anonymous types don't have too much of a use, it's better to use plain tuples/records/classes depending on the situations.
yea was just trying to be lazy
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.