Anonymous Types in C#

Hi Friends,

In today’s discussion, we’ll see anonymous types. Well by books, Anonymous types are strongly typed, immutable with a bunch of properties. we basically create the instance of anonymous types by basically providing properties value like shown below.

so, I have created a var person and created an instance the next thing is anonymous
initializer, and this is created a whole new class behind the scenes. In order to inspect the same what you can do is inspect the same in Reflector using Ildasm. It will show you a bunch of scary things out there. but, for this discussion, am keeping the things fairly simple and just focusing on the high level things.
var person= new { FirstName = “Rahul”, LastName = “Sahay” };

now, there are certain catch with the same, If i try to change the order of the same,
person = new { LastName = “scott”,FirstName = “dave” }; // will popup error

i cannot do that because, the 1st one which i created has got the same in reference like below

let me just show you the var indication.



Now, when i run the same it will print the below output like below:



so, having said to my earlier statement anonymous types are strongly typed. you will get fairly good intellisense while writing the code as shown below.


also, one more point when i mentioned that anonymous types are immutable. this can be referred as below like



so, it’s says that it’s a readonly property cannot be intervened again, once initialized.

now, we have liberty of having embedded anonymous types as well like shown below



now, when i run the same, it will print the below string inside braces obviously.



However, this is ok when i have to print one variable like person kind of thing,how about
when i have to take care of bunch of values, so in this case i need to consider Implicitly Typed Arrays like shown below


obviously, since i have to loop through the array, so i have changed the printing condition and now, the output would go like this



So, now with this i would like to wrap this discussion. Till then, stay tuned and Happy Coding.

Happy Coding

Thanks, Rahul Happy Coding