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…
At this point, you add the name of the class….
then invoke the generate from usage smart tag
At which point we are done. Here is the class that VB generated…
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.