Fadzai Chamba

I disagree with everything I just said

No longer anonymous types

I’m thoroughly enjoying the nice new features in VS2010 and the little features offer the best wow moments for me.

I was working on an app a couple of days ago that used LINQ and anonymous types and I now had to pass the result of the query to a procedure in another class for storage. This meant I had to write out a class and replace the reference to the anonymous type with the name of the class I had been using.

I tried something new first, by writing the intended name of the class, and generating the class from usage. Doing this was a breeze as I accomplished everything in one step from VB. It generated auto implement properties based on the object initializer and I thought this was cool.

Here is a step-by-step guide on how to accomplish this…

anony-step1

At this point, you add the name of the class….

anony-step2

then invoke the generate from usage smart tag

anony-step3

At which point we are done. Here is the class that VB generated…

anony-step4

I think it is so cool, the way VS2010 makes you more productive. All I had to do was 4 keystrokes, A-p-p-<space> (in the context of the example I am using) and then all was well. The method in the class I was working on now had to reference the name of the class that I specified.

There are some differences however in that there is one method of anonymous types in VB that makes the type immutable, and you can have another way that you can edit the values. C# generates immutable anonymous types only. If you want similar semantics for your generated class, you will have to expand the properties and implement them as write-once, read-only (in which case you will have to call a constructor as opposed to using object initializers). I’ll get around to doing this in C# and posting on how to do it in that language although I can’t imagine the process being too different.

Hope this helps, happy coding.

Published Mon, Jan 11 2010 11:50 AM by Fadzai Chamba

Comments

# re: No longer anonymous types@ Monday, February 15, 2010 6:20 PM

I never did get back to posting the C# version. Well, in C# you can achieve the same thing but it is a mroe involved procedure.

You start by typing the intended name for your class. At this point you then click on the smart tag and generate the class from usage.

Next, for each property, you click the smart tag and generate from usage.

It's not the breeze you get from VB but you still get the job done, and it beats the life out of writing the code for the new class out for youself.

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Please add 1 and 7 and type the answer here: