FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
Development Tools
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
January 10, 2008

Inside Visual Studio 2008

(Page 3 of 6)

Some 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:

public string ContactName { get; set;}

The compiler automatically expands this code like this:

private string contactName; public string ContactName { get { return contactName; } set { contactName = value; } }

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:

Person person = new Person { FirstName="Dino", LastName="Esposito", Age=24 };

The idea is extended to collections, as in this code:

List<Person> friends = new List<Person> { new Person { FirstName="Nancy", LastName="Davolio", Age=28 }, new Person { FirstName="Andrew", LastName="Fuller", Age=35 }, : };

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.

Previous Page | 1 Visual Studio 2008 | 2 Multitarget Projects | 3 Some C# and VB Syntactic Sugar | 4 Richer Languages Beyond the Sugar | 5 LINQ Facilities | 6 Visual Studio 2008 Projects Next Page
TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK