January 10, 2008
Inside Visual Studio 2008Some C# and VB Syntactic Sugar
In Visual Studio 2008, C# and Visual Basic offer a few time-saving features that basically give the compiler the burden of creating some required code. In the end, these features are just syntactic sugar that make C# and VB programming easier and more pleasant.
"Automatic properties" is a feature that instructs the compiler to automatically add a default implementation for the getter/setter methods of a class property. This code is now perfectly legal in a class compiled with the newest C# compiler:
The compiler automatically expands this code like this:
Automatically generated get/set properties are not equivalent to public fields. From a metadata perspective, properties and fields are quite different entities. The idea here is that you just delegate to the compiler the creation of some plumbing code, in the most common and simple scenario. At a later time, you can always come back and provide your own getter/setter methods.
Object initializers are another piece of syntactic sugar to speed up the creation of the code that initializes an object. Instead of going through a potentially long list of assignment instructions, you can code it like this:
The idea is extended to collections, as in this code:
Compared to the syntax required in Visual Studio 2005, the savings is pretty clear and can easily sum up to tens of lines of code for large procedures.
|
|
||||||||||||||||||||||||||||||
|
|
|
|