Automatic Properties, Collection Initializers, and Implicit Line Continuation support with VB 2010

[In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

This is the eighteenth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release.

A few days ago I blogged about two new language features coming with C# 4.0: optional parameters and named arguments

Today I’m going to post about a few of my favorite new features being added to VB with VS 2010: Auto-Implemented Properties, Collection Initializers, and Implicit Line Continuation support.

Auto-Implemented Properties

Prior to VB 2010, implementing properties within a class using VB required you to explicitly declare the property as well as implement a backing field variable to store its value. 

For example, the code below demonstrates how to implement a “Person” class using VB 2008 that exposes two public properties - “Name” and “Age”:

image 

While explicitly declaring properties like above provides maximum flexibility, I’ve always found writing this type of boiler-plate get/set code tedious when you are simply storing/retrieving the value from a field.  You can use VS code snippets to help automate the generation of it – but it still generates a lot of code that feels redundant.  C# 2008 introduced a cool new feature called automatic properties that helps cut down the code quite a bit for the common case where properties are simply backed by a field.  VB 2010 also now supports this same feature. 

Using the auto-implemented properties feature of VB 2010 we can now implement our Person class using just the code below:

image

When you declare an auto-implemented property, the VB compiler automatically creates a private field to store the property value as well as generates the associated Get/Set methods for you.  As you can see above – the code is much more concise and easier to read.

The syntax supports optionally initializing the properties with default values as well if you want to:

image

You can learn more about VB 2010’s automatic property support from this MSDN page.

Collection Initializers

VB 2010 also now supports using collection initializers to easily create a collection and populate it with an initial set of values.  You identify a collection initializer by declaring a collection variable and then use the From keyword followed by braces { } that contain the list of initial values to add to the collection. 

Below is a code example where I am using the new collection initializer feature to populate a “Friends” list of Person objects with two people, and then bind it to a GridView control to display on a page:

image

You can learn more about VB 2010’s collection initializer support from this MSDN page.

Implicit Line Continuation Support

Traditionally, when a statement in VB has been split up across multiple lines, you had to use a line-continuation underscore character (_) to indicate that the statement wasn’t complete. 

For example, with VB 2008 the below LINQ query needs to append a “_” at the end of each line to indicate that the query is not complete yet:

image

The VB 2010 compiler and code editor now adds support for what is called “implicit line continuation support” – which means that it is smarter about auto-detecting line continuation scenarios, and as a result no longer needs you to explicitly indicate that the statement continues in many, many scenarios.  This means that with VB 2010 we can now write the above code with no “_” at all:

image

The implicit line continuation feature also works well when editing XML Literals within VB (which is pretty cool).

You can learn more about VB 2010’s Implicit Line Continuation support and many of the scenarios it supports from this MSDN page (scroll down to the “Implicit Line Continuation” section to find details).

Summary

The above three VB language features are but a few of the new language and code editor features coming with VB 2010.  Visit this site to learn more about some of the other VB language features coming with the release. 

Also subscribe to the VB team’s blog to learn more and stay up-to-date with the posts they the team regularly publishes.

Hope this helps,

Scott

32 Comments

  • Nice to see VB.NET supports more C# like features

  • thats cool, thank you.

    Hey Scott, what about new features of Toolbox? Actually I don't like the current toolbox, the first version of it (vs.net-2003) more useful. Is there any idea to return back or give us an option for this?

  • Had a client request that I write some code for him in VB10. Auto properties in the new version saved my sanity.

  • wow , but all these features already existed for c# for long.

  • Hi Scott,

    In C# auto properties, it's possible to specify a different access modifier for the setter :

    public string { get; private set; }

    Is there a way to do that for VB auto properties ?

  • Hi Huthaifa and vik20000in,

    Let us not antagonize our VB friends. It is worth noting that some of the features Scott mentions are not yet implemented in C#.

    C# 4.0 does not yet implement:
    - XML Literals
    - Default values for automatically generated properties (yes you can auto generate the properties but not assign a default value in the same line of code).

    Microsoft does appear to be following a strategy of evolving the features together so over time we should see more parity.

    Dave

  • Great additions here, even though yes they have been in C# for a while now.

    I'm loving the automatic properties addition, but the only thing I'm disappointed with them is that there doesn't seem to be any support for read-only automatic properties. C# has this (you just set the setter to 'private') and it doesn't seem such a stretch to add in a readonly keyword to the property declaration: ReadOnly Property Name As String, which would just implicitly create a private setter.

    If this has been added already I apologise; I'm testing it in the RC now but it doesn't work.

  • Nice article, but it make me feel like C# is more advanced than VB! I've used C# from .net framework 1.0 and know few about vb.net.

  • Very nice article scott, but with every new release of .net framework, vb.net is adopting more and more features of c#.. humm, interesting, don't you?

  • @vik20000in - Yup. And on the other side of the coin if you read Scott's last article on optional parameters getting added to C# you could comment that those have existed in VB for a long time as well.

  • I like the curly braces.
    :-)

  • I must say that it's really "strange" to see the curly braces in the world of VB.Net but it's definitely a welcome change. Great job VB.Net team!

    @vik20000in - One of the goals of .Net 4.0 was to bring C# and VB.Net as close to on par with each other as possible.

  • Am i missing something or does auto properties make a huge metaphorical turn around the block to turn a property into a variable?
    No need to set\get? check.
    Define initial value? check.
    Small size? check.
    Can you convert a property into a more elaborate property? Yes, but you can do that to a variable also.

  • Is there any way (via third-party addon, perhaps) that we can add automatic properties to VB.Net 2008 right now?

  • @Murat,

    >>>>>>>>> Hey Scott, what about new features of Toolbox? Actually I don't like the current toolbox, the first version of it (vs.net-2003) more useful. Is there any idea to return back or give us an option for this?

    Can you provide more details on what you don't like about the Toolbox?

    Thanks,

    Scott

  • @Thomas,

    >>>>>>> In C# auto properties, it's possible to specify a different access modifier for the setter :

    My understanding right now is that it isn't possible to do this (meaning you can't have one be public and one private). Instead you'd need to explicitly declare the property for that scenario.

    Hope this helps,

    Scott

  • @Steve,

    >>>>>>>>> I'm loving the automatic properties addition, but the only thing I'm disappointed with them is that there doesn't seem to be any support for read-only automatic properties. C# has this (you just set the setter to 'private') and it doesn't seem such a stretch to add in a readonly keyword to the property declaration: ReadOnly Property Name As String, which would just implicitly create a private setter.

    Unfortunately I don't think this is supported for VB 2010. I agree it would be a good feature to have in the future though.

    Thanks,

    Scott

  • @facrtu,

    >>>>>>> Very nice article scott, but with every new release of .net framework, vb.net is adopting more and more features of c#.. humm, interesting, don't you?

    Well if you look at my previous post you'll find that C# is also adopting more features of VB. Thankfully they are sharing their good features back and forth.

    Thanks,

    Scott

  • Hi daxmax,

    > Can you convert a property into a more elaborate property? Yes, but you can do that to a variable also.

    But you will have *lots* of problems if you start with a public field and later try changing it to a property (especially if you are writing a library or doing databinding).

    Note that fields and implicit properties are not the same thing. Importantly if you add a reference to a library (.dll) that exposes a public field such as:
    public string MyField;

    Then later changed that to a property such as:
    public string MyField {get; set;}

    You actually need to do a recompile against the referenced library and cannot just drop in the replacement DLL.

    Of course, lots of the databinding infrastructure also requires properties (instead of fields), along with UI designers etc.

    Regards,

    Dav

  • I thought you had committed yourself to feature parity between C# and VB. But the automatic props are totally different between the two languages.

    VB will allow you to make a public only (which means in reality it is just a field) property with a default value.

    C# allows you make a mixed access property, but it is impossible to set a default value (except in the constructor)

    Why to total divergence yet again?

  • Great! C# & VB Compilers and IDE features should be somehow similar as most of .Net teams over the world are using both languages. this will make it easier for C# & VB developer to do peer programming

  • Yay for Auto-Implemented Properties ! Whenever I switch from C# to VB I always miss that feature ( yeah, I can write the property quickly with snippets, but nevertheless it is 9 lines of code )

    It would be interesting if we can also get an option to define what variable should the property use as a backend. For example quite often I write asp.net user controls in which I need to expose some property of control inside the user control, as a property on the user control.
    So instead of
    Public Property Title as String()
    Get
    Return lblTitle.Text
    End Get
    Set(ByVal value as String)
    lblTitle.Text
    End Set
    End Property
    to have something like
    Public Property Title as String() Uses lblTitle.Text

  • coming back to VB 6 , GREAT! :)))

  • re: Is there any way (via third-party addon, perhaps) that we can add automatic properties to VB.Net 2008 right now?

    Yup. Try MZ-Tools. Been there since VB6 and for all prior versions of VB.NET and it's nowhere near as restrictive as the Automatic Properties feature. You can choose get/set public/private/friend etc and you invoke it by simply declaring the private variable and right clicking to convert it to a property.

  • Reading VB is like reading italian. Long and bloated.

  • Thats the same like saying: "Reading C# is like reading mathematic equations. Short and cryptic"
    It's just hard to read, because you are not accustomed to the syntax. You would adapt to either syntax rather quickly after programming with corresponding language for a while.

  • It's sad that initialization of auto implemented properties hasn't been addressed in C#, despite all the talk of co-evolution, and the strong support for the feature on Connect:

    https://connect.microsoft.com/VisualStudio/feedback/details/361647/add-initialization-to-automatic-properties-in-c

  • Very good article !

  • Auto-implemented properties will be a wonderful time-saver once I upgrade. I'm so glad to see that.

    Regarding collection initializers, is there some under-the covers difference between this line from a VB9 app:

    Dim zipTypes As New List(Of String)(New String() {"PostalCode", "MailingPostalCode", "BillToPostalCode"})

    and the new "From" syntax version:

    Dim zipTypes as New List(Of String) From {"PostalCode", "MailingPostalCode", "BillToPostalCode"}

    or is it just cosmetic? I'm not seeing the big deal. But I don't really know what's going on regarding performance.

  • Christopher, the difference is the new collection initializer syntax doesn't require allocation of the String(), whereas the first example does. (i.e. it'll use less memory and run faster).

    The other thing is the collection initializer syntax can also be used for dictionaries or types that implement "the collection pattern". Some of these other types may not have an overload that takes in an array like List(Of T) does.

  • Thanks! I'd think the performance side of that would only matter with massive repetition or maybe really huge arrays, but yeah. And I was thinking that while all the sources I've seen talk about this seem to concentrate on Lists, the real benefit (at least in my use scenarios) would be for Dictionaries (or Hashtables?).

  • Thanks for this, just started work on an MVC e-commerce site and was looking for the syntax for the newly implemented feature when I stumbled on the post. Cool progress for VB.Net

Comments have been disabled for this content.