✅ Anonymous type
So while is was reading about LINQ I stumbled upon an example that only works with
var
due to being an anonymous function.
They showed the following:14 Replies
what does
new { ... }
yield here, an anonymous type but what is it deducted too
they wrote it as if only var
would work as there is no explicit type one could write there that'd match it
does it generate a basic struct with name and phone as members and uses init list to initialize them ({get; init;}
)
I come from C++ and this would be deducted to a type one could type/refer to explicitly, if not, it would not compile to begin with.https://sharplab.io/#v2:EYLgtghglgdgPgNwgJwASojA9jVBeVGAUwHdUBvGCMI/VAIipvoBpUAHACxyL3oAYAbAA5RY0fQC+AbiA===
the compiler generate a generic class
SharpLab
C#/VB/F# compiler playground.
would this semantically be a record?
it looks like it to me but i cant say for certain
looks like yeah
I tried to re assign the value
the record implement IEquatable<T> and the anonymous object doesn't
huh
this is bizarre, tbh i didnt even think this was possible
that would be weird to compare 2 anyonymous objects that seems legit for me xD
I've got bad internet here on holiday, would someone be able to paste the code
from the playground
nvm it loaded finally, ok makes sense - I already dont like that lol.
you still can create a record or a class if you don't want use anon type
https://learn.microsoft.com/en-us/dotnet/standard/base-types/choosing-between-anonymous-and-tuple for your reading pleasure
Choosing between anonymous and tuple types - .NET
Learn when it's appropriate to choose between anonymous types, and tuple type.
anon types are old, introduced in C# 3
You should still be able to reference it as an
object
instead of using var
. If you paste the code, hovering the query variable will reveal the declared type inside IEnumerable<>
. var
is just a shorthand that gets replaced with the declared type of the value you give it, nullable if it's a reference type.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.