C
C#2y ago
PatrickG

❔ 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
Relevant
Relevant2y ago
Because you're converting the anonymous objects to object Which is not the same
PatrickG
PatrickGOP2y ago
ok I just changed object to dynamic and seems to work
Relevant
Relevant2y ago
Probably not the proper way to do it, but that will at least verify the issue
PatrickG
PatrickGOP2y ago
what is the proper way without creating a class ?
Relevant
Relevant2y ago
create a class
PatrickG
PatrickGOP2y ago
hehe ok
Axiss
Axiss2y ago
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.
Thinker
Thinker2y ago
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.
PatrickG
PatrickGOP2y ago
yea was just trying to be lazy
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server