25 July 2007

.NET 3.5 Language Enhancements

LINQ may be getting the most attention in the forthcoming .NET 3.5, but there are also several new language features that add functionality and make life easier for the programmer. John Papa explains more...

While Visual Studio 2008, the several variations of LINQ, and the ADO.NET Entity Framework are getting a lot of attention in the upcoming .NET Framework 3.5, there are also several key language enhancements on the near horizon. Many of the language enhancements (which will be found in VB 9 and C# 3.0) are the foundation of these more prominent new technologies. This article is a primer for some of the key enhancements that will be introduced with the .NET Framework 3.5 and how they relate to each other.

There are several .NET language enhancements to be introduced with Visual Studio 2008 including implicitly typed variables, extension methods, anonymous types, object initializers, collection initializers and automatic properties. These language enhancements, along with features like generics, are critical to the use of some of the new features, such as LINQ with the ADO.NET Entity Framework. What can be confusing is that these features are often referred to in the same conversation as LINQ. Because of this relation by association, you may be led to believe that these features are part of LINQ. They are not; they are part of the .NET Framework 3.5 and the VB 9 and C# 3.0 languages. They are very valuable in their own rights as well as playing a huge role for LINQ.

This article will demonstrate and discuss several key language features including:

  • Automatic Property setters/getters
  • Object Initializers
  • Collection Initializers
  • Extension Methods
  • Implicitly Typed Variable
  • Anonymous Types

415-figure4-revised.gif

Figure 1 – Many of the New Language Enhancements

Automatic Properties

Since creating classes by hand can be monotonous at times, developers use either code generation programs and IDE Add-Ins to assist in creating classes and their properties. Creating properties can be a very redundant process, especially when there is no logic in the getters and setters other than getting and setting the value of the private field. Using public fields would reduce the code required, however public fields do have some drawbacks as they are not supported by some other features such as inherent data binding.

One way to get around having to type the code for a private field and its public property getter and setter is to use a refactoring tool. However, there is a new language feature called Automatic Properties that allows you to type less code and still get a private field and its public getter and setter. You declare the automatic property using a shortcut syntax and the compiler will generate the private field and the public setter and getter for you. For example, Figure 2 shows a Customer class that has several private fields that are exposed through a series of corresponding public properties. This class has 4 properties including one that is of the class type Address.

Figure 2 – Customer Class using Explicit Fields, Getters and Setters

Figure 3 shows how the same result can be achieved through automatic properties with less code than Figure 2. The Customer class in Figure 3 uses automatic properties to create the class’ properties without writing all of the code to declare a field and its property getter and setter.

Figure 3 – Customer Class using Automatic Properties

Object Initializers

It is often helpful to have a constructor that accepts the key information that can be used to initialize an object. Many code refactoring tools help create constructors like this with .NET 2. However another new feature coming with .NET 3.5, C# 3 and VB 9 is object initialization. Object Initializers allow you to pass in named values for each of the public properties that will then be used to initialize the object.

For example, initializing an instance of the Customer class could be accomplished using the following code:

However, by taking advantage of Object Initializers an instance of the Customer class can be created using the following syntax:

The syntax is to wrap the named parameters and their values with curly braces. Object Initializers allow you to pass in any named public property to the constructor of the class. This is a great feature as it removes the need to create multiple overloaded constructors using different parameter lists to achieve the same goal. While you can currently create your own constructors, Object initializers are nice because you do not have to create multiple overloaded constructors to handle the various combinations of how you might want to initialize the object. To make matters easier, when typing the named parameters the intellisense feature of the IDE will display a list of the named parameters for you. You do not have to pass all of the parameters in and in fact, you can even use a nested object initialize for the BusinessAddress parameter, as shown below.

Collection Initializers

Initializing collections have always been a bother to me. I never enjoy having to create the collection first and then add the items one by one to the collection in separate statements. (What can I say, I like tidy code.) Like Object Initializers, the new Collection Initializers allow you to create a collection and initialize it with a series of objects in a single statement. The following statement demonstrates how the syntax is very similar to that of the Object Initializers. Initializing a List<Customer> is accomplished by passing the instances of the Customer objects wrapped inside of curly braces.

Collection Initializers can also be combined with Object Initializers. The result is a slick piece of code that initializes both the objects and the collection in a single statement.

The List<Customer> and its 3 Customers from this example could also be written without Object Initializers nor Collection Initializers, in several lines of code. The syntax for that could look something like this without using these new features:

Extension Methods

Have you ever looked through the list of intellisense for an object hoping to find a method that handles your specific need only to find that it did not exist? One way you can handle this is to use a new feature called Extension Methods. Extension methods are a new feature that allows you to enhance an existing class by adding a new method to it without modifying the actual code for the class. This is especially useful when using LINQ because several extension methods are available in writing LINQ query expressions.

For example, imagine that you want to cube a number. You might have the length of one side of a cube and you want to know its volume. Since all the sides are the same length, it would be nice to simply have a method that calculates the cube of an integer. You might start by looking at the System.Int32 class to see if it exposes a Cube method, only to find that it does not. One solution for this is to create an extension method for the int class that calculates the Cube of an integer.

Extension Methods must be created in a static class and the Extension Method itself must be defined as static. The syntax is pretty straightforward and familiar, except for the this keyword that is passed as the first parameter to the Extension Method. Notice in the code below that I create a static method named Cube that accepts a single parameter. In a static method, preceding the first parameter with the this keyword creates an extension method that applies to the type of that parameter. So in this case, I added an Extension Method called Cube to the int type.

When you create an Extension Method, the method sows up in the intellisense in the IDE, as well. With this new code I can calculate the cube of an integer using the following code sample:

As nice as this feature is I do not recommend creating Extension Methods on classes if instead you can create a method for the class yourself. For example, if you wanted to create a method to operate on a Customer class to calculate their credit limit, best practices would be to add this method to the Customer class itself. Creating an Extension method in this case would violate the encapsulation principle by placing the code for the Customer’s credit limit calculation outside of the Customer class. However, Extension Methods are very useful when you cannot add a method to the class itself, as in the case of creating a Cube method on the int class. Just because you can use a tool, does not mean you should use a tool.

Anonymous Types and Implicitly Typed Variables

When using LINQ to write query expressions, you might want to return information from several classes. It is very likely that you’d only want to return a small set of properties from these classes. However, when you retrieve information from different class sources in this manner, you cannot retrieve a generic list of your class type because you are not retrieving a specific class type. This is where Anonymous Types step in and make things easier because Anonymous Types allow you to create a class structure on the fly.

Notice that the code above creates a new instance of a class that describes a dog. The dog variable will now represent the instance of the class and it will expose the Breed, Coat and Ferocity properties. Using this code I was able to create a structure for my data without having to create a Dog class explicitly. While I would rarely create a class using this feature to represent a Dog, this feature does come in handy when used with LINQ.

When you create an Anonymous Type you need to declare a variable to refer to the object. Since you do not know what type you will be getting (since it is a new and anonymous type), you can declare the variable with the var keyword. This technique is called using an Implicitly Typed Variable.

When writing a LINQ query expression, you may return various pieces of information. You could return all of these data bits and create an Anonymous Type to store them. For example, let’s assume you have a List<Customer> and each Customer has a BusinessAddress property of type Address. In this situation you want to return the CompanyName and the State where the company is located. One way to accomplish this using an Anonymous Type is shown in Figure 4.

Figure 4 – Using Anonymous Types with LINQ

Pay particular attention to the select clause in the LINQ query expression. The select clause is creating an instance of an Anonymous Type that will have a Name and a State property. These values come from 2 different objects, the Customer and the Address. Also notice that the properties can be explicitly renamed (CompanyName is renamed to Name) or they can implicitly take on the name as happens with the State property. Anonymous Types are very useful when retrieving data with LINQ.

Wrapping Up

There are a lot of new language features coming with .NET 3.5 that both add new functionality and make the using of existing technologies easier. As we have seen in the past, when new technologies have been introduced, such as with generics, they often are the precursors to other technologies. The introduction of Generics allowed us to create strongly typed lists. Now because of those strongly typed lists of objects we will be able to write LINQ query expressions against the strongly typed objects and access their properties explicitly even using intellisense. These new features such as Object Initializers and Anonymous Types are the building blocks of LINQ and other future .NET technologies.

Keep up to date with Simple-Talk

For more articles like this delivered fortnightly, sign up to the Simple-Talk newsletter

This post has been viewed 158412 times – thanks for reading.

Tags: , , ,

  • Rate
    [Total: 570    Average: 4/5]
  • Share

John Papa

View all articles by John Papa

  • Anonymous

    Lost you halfway through
    Sorry John but I lost you halfway through this article

  • The SQL Server Thought Police

    Re: Lost you halfway through
    I was with you right through to the end, though I was slightly flushed and short of breath. Great article and regards to Kadi

  • Joe

    Whats the point in Anonymous Properties?
    I don’t get it. Why not just make the field public?

  • Joe

    RE: “Why not make the field public”
    Joe … you can just make the field public, however some tools in .NET require that you use a property getter and/or setter. For example, the data binding tools in .NET can see publicly exposed property getters but cannot be bound to public fields.

    That said, automatic properties are not earth shattering by any means. Especially iyou use tools like Resharper or Code Rush to create the fields and getters/setters for you. Tey are just another shortcut that gives you another tool in your belt.

  • John Papa

    Kadi
    To “The SQL Server Thought Police” … Kadi appreciates the sentiment 🙂

    Oh …. and that last comment was by me to Joe, not by Joe to Joe 🙂

  • Alex Egg

    C# & Javascript
    It’s good to see C# becoming more a dynamic language. I’m starting to see lots of parallels to javascript in your above examples… and javascript is awesome.

  • Anonymous

    Nice
    Thanks – that’s a great explanation of the new features

  • Jacob Cameron

    Anonymous Type Flip flop
    In traditional ASP (VB Script) there was no types. Then came .NET and Strongly Typed. Now, we are back to no types. Thanks Microsoft, took you 10 years to get right back where we were 10 years ago.

  • Frederik Gheysels

    re: anonymous type flip flop
    Jacob: what you’re saying is not correct.
    Yes, it is true that .NET 3.5 will now support something like a ‘var’ variable, but this is not the same as the ‘variant’ type that existed in the old days.
    The ‘implicit type’ now lets you assign an object of a certain type to it, but once the ‘var’ is assigned, you cannot assign an object to it that is of another type.
    Moreover, you’ll have to initialize the implicit type at the moment that you declare it and you cannot initialize it to NULL.

  • Mark Bjerke

    I like the Object Initializer Work
    For sites that currently use JavaScript Object Notation and moving towards .Net this is a pretty big deal. Currently a lot of data moves across the wire as JSON.

    In essence with JSON you hava an anonymous initializer for a generic dictionary type of key value pairs.

    Now you have the specific target class as part of the syntax. Also I now have a .Net class that is type checked for me.

    This is a major advance over what I see being done with a lot of AJAX code.

    Don’t laugh there is lots of JSON moving across the internet.

  • abrichardson

    can’t wait
    I can’t wait for these new features! I strive for cleaner code and this will certainly have it’s place in my Utility-Belt.

    In reply to the question about using public fields…Why would you want to do that!? The idea of using properties is to abstract and validate ( among other reasons ) Using public fields violates OOP at the foundation.

    Great article!!!

  • abrichardson

    RE: C# & Javascript
    Javascript is not a strongly typed language where C# is. While it’s nice to have the power to toss any type into any variable at anytime, that can get you in a lot of trouble down the road everytime. 😉

    What c# does ‘dynamicaly’ is very much different than what Javascript or PHP can do. Note: I LOVE Javascript and PHP both 😀 I’m not knocking them…I’m just comparing apples and oranges to apples and oranges.

  • Anonymous

    What does it all cost?
    Hi John,
    Just wondering what is the cost of LINQ code?
    Do we end up with MSIL that is just as efficient as the ‘old’ way of doing things or in fact is it even better?
    i.e. For you example I guess I would have used an iterator to build a list of items from ‘FL’
    I assume they have done some benchmarks, do you know of any results?
    Thanks
    Bob

  • Anonymous

    What does it all cost?
    Hi John,
    Just wondering what is the cost of LINQ code?
    Do we end up with MSIL that is just as efficient as the ‘old’ way of doing things or in fact is it even better?
    i.e. For you example I guess I would have used an iterator to build a list of items from ‘FL’
    I assume they have done some benchmarks, do you know of any results?
    Thanks
    Bob

  • Frederik Gheysels

    auto-properties
    abrichardson: what’s the use of public fields ?
    Well, indeed… Using public fields violates the ‘encapsulation’ rule of OO. However, what’s the use of public gettable/settable properties that do nothing more then just delegating the value to / from the private member ?
    Ok, you need properties for databinding, but if these properties have no further logic, what’s the use of them ? Using properties is then indeed more puristic, but in fact you’re typing a lot more just to achieve the same result.
    (Although, I also use public properties instead of public fields directly, but surely, these auto-properties will be very helpfull).

  • Timothy Humphrey

    Public fields
    I use public fields all the time, primarily because it’s just syntactically easier to write than the corresponding “proper” property getter and setter. However they do compile down differently than properties do so if I were writing a library to be consumed by other people I’d bite the bullet and make a property. But with automatic properties I’ll no longer have a reason to use public fields over properties.

  • Richard

    Error in Cube function
    In C#, “^” is the XOR operator, not the exponentiation operator. The direct translation would be:

    return (int)Math.Pow(someNumber, 3);

    A more efficient alternative would be:

    return someNumber * someNumber * someNumber;

  • Anonymous

    C# and Javascript
    John – thanks for the article – it’s great.
    I also couldn’t help notice the similatrities to Javascript. I do a lot of Javascript with objects, prototype-programming, JSON’s etc, and am aware of the problems concerning doing over-dynamic code… I’m wondering what how MS thinks of handling these problems when it comes to C#. alotta-debugger? 🙂

  • Anonymous

    Automatic Properties – Not for real programs.
    The problem with Automatic Properties is that I can no longer validate values before my internal field is changed – might as well make a public field (except for tool support). How do I raise an event once a property has changed?

    Seems like the feature was added without any thought of how usefull it really is.

    They could have done a MUCH better job by adding more advanced refactering combined with advanced templates to Visual Studio..

    Good Article

  • Anonymous

    Re: Automatic Properties – Not for real programs
    If you want the changing of a property to fire an event, or execute a method you would use the normal property structure. However if you just want to create normal get/set or readonly properties then automatic properties is a quick way to do it. Not ever property needs to fire an event or execute a method.

  • Anonymous

    Automatic properties
    The reason you should use properties instead of public vars is you might need to add some logic later when you get/set the value. Sure you can change the var into a property later and your code will still be compatible, but binary compatibility is broken.

    For example you have dllA that somewhere inside sets the value of a var in dllB, You decide to change that var to a property. You must now recompile dllA for it to operate. And in some languages(not C#, and I don’t think VB), the code of dllA may have to change.

  • Daniel Penrod

    For me or for $??
    Is MS easing the language to compete or to make it easy for me? It seems to me like all these Castle spawned philosophies are steering MS, but the bottom line is MS is more concerned about dollars than they are about saving my fingers. I have to question their intentions here. Are they afraid C# is to complicated compared to something like Ruby or Boo? Not that cutting corners with Automatic Properties or var(ing) something out is a bad thing – but I hope it doesn’t start becoming a trend with each new release of the framework (TO DUMB IT DOWN to save a second or two in typing). They are suppose to save my fingers with VS not with the language per say. Sounds to me like they are adopting the Ruby and Boo philosophy more than anything else. Unless MS stops getting steered by these finger/wrist saving language philosophies, C# will be nothing more than VBScript on Crack by the year 2050. It is hard to say (at this time) if the ease of Ruby and Boo type languages will last the test of time. The higher the level you make a language the more dependent you become on the supporting levels / framework beneath it. This is a good and bad thing. There has to be a balance and a trade off. I don’t want this comment to sound negative cause I think MS didn’t do anything to extreme here with 3.5. I just hope I can say the same thing 10 years from now. But there again, here comes MVC….

  • Anonymous

    artile
    I thought you needed more ways to talk about objectives and rebutals. Thank you though it was nice information not enough.

    Thank you,
    x

  • Gerald

    what the hell was this about? I’m lost
    I think there was not enough information however,it was good but needed more. It seemed like a Ross Perot way of show and tell but if you could give more information to read and not as much computer screen wording it would be better. I hope you will do more to make it better I think you should rewrite the information taking out the rest of the bull shit.

    Good luck to you,
    Gerald

  • Anonymous

    what?
    These comments are kind of silly.

    All the ‘dynamic’ things you’re seeing in C# 3.0 is just compiler black magic, C# will never be a dynamic language, VBX will be though (it’s running on the DLR). All vars are typed, all anonymous types are actually created at compile time. The only new overhead you’ll see with this technology is how long it takes to compile. As for more overhead with LINQ, I’m sure it takes advantage of yield and enumeration better than most developers can, so it’s most likely quicker at the MSIL end.

    /rant

  • DIvanov

    Public Fields vs. Automatic Properties
    As I remember Automatic Properties provide with one more pretty good feature – limitation of access to get or set. E.g., you can modify the property CompanyName in the following way:

    public string CompanyName { get; PRIVATE set; }

    In this case the property will be “read only”. This is definitely not supported by public fields.

  • Deepak Vasa

    Extension Methods
    I came across your article while googling around to find new features in .NET 3.5 frame work. Your article is quite good and informative.

    I would like to point out that we have been using some thing similar to Extension Methods called Apply functions in a language called ACE (www.teratext.com) for the last 7 years. It’s good to see .NET implementing it.

  • Anonymous

    nice article
    I think these features will be really handy, and I think MS are doing the right thing in providing a choice for devs – i.e to be rigidly OO, or use RAD shortcuts where appropriate.

  • Anonymous

    Excellent article and useful new features.
    No wonder you were a trainer once. You explained it really well. Excellent article.

  • Erik E. Van Vliet

    Linq and Automatic Properties
    Shame Linq seems to have been devoloped by another group of developers. Why?

    The linq classes that are automatically generated by visual studio 2008 and visual web developer 2008 do not use the shorthand notation for properties, but instead uses the longhand notation:

    [Table(Name=”Sheeps”)]
    public class Sheep
    {
    private string _AnimalID;
    private string _Name;

    [Column(IsPrimaryKey=true)]
    public string AnimalId
    {
    get
    {
    return _AnimalId;
    }
    set
    {
    _AnimalId = AnimalId;
    }
    }

    [Column]
    public string Name
    {
    get
    {
    return _Name;
    }
    set
    {
    _Name = Name;
    }
    }
    }

    (Not that it’s your fault; just thought you’d like the additional info)

  • Anonymous

    like python
    Something like the python language

  • nem

    RE: “Why not make the field public”
    There is another very good reason for properties. If your design is moving towards using Interfaces, (which I highly suggest)any variable that needs to modified in class that you want to extract as an interface needs to be set as a public Property or a Public Method to begin with. If you designed your classes with properties in mind to begin with it is very easy to use visual studio to extract your interfaces from your Objects on the fly. If you had used public variables to begin with then you will have to change them to public properties or public methods to make them available for modification through the interface.

    So it is to your advantage to use properties to begin with in order to save time, and for code reuse.

    NEM

  • Sudhir Kesharwani

    Excellent Work
    hey excellent article, nicely structured and explained. i liked the short examples that made the things more clearer.

    good work john

  • kvenr99

    Great Job
    you have explained lot of new features in one topic, that’s great work. we would like you to write many more articles like this.

  • kenny

    question
    how do you use a loop to intialise the objects? rarely you create a list of objects by such hardcoding:

    List<Customer> customerList = new List<Customer> {
    new Customer {ID = 101,
    CompanyName = “Foo Co”,
    BusinessAddress = new Address {State=”FL”}}, new Customer {ID = 102,
    CompanyName = “Goo Co”,
    BusinessAddress = new Address {State=”NY”}},
    new Customer {ID = 103,
    CompanyName = “Hoo Co”,
    BusinessAddress = new Address {State=”NY”}},
    new Customer {ID = 104,
    CompanyName = “Koo Co”,
    BusinessAddress = new Address {State=”NY”}}
    };

  • Rohit Sankhe

    Good Article
    Althought I liked the article, I still think that the basic nature of LINQ makes people loose the link within the article…

  • Stoke

    Thanks
    Thanks JohnP. Still no MustInherit implementation though. -cry-

  • Anonymous

    Good Article

    Good work. Thanks

  • Anonymous

    Good Job
    good work.Thanks

  • Oscar Luis

    To DIvanova about “readonly properties”
    You could have the same effect by using readonly keyword attribute on public fields, something like:
    public readonly int Age;
    The only thing with this approach is that you can only assign the value on the class’ constructor.
    I think that when there’s no data binding or need to change the value, readonly public fields are a good choice (FxCop says the same).

    Excelent work,

  • Manjeev Singh

    Good job
    Hye Dear you are doing grate job here. I think most of people get’s grate help through your article.
    thank’s alot

  • Pablo

    Got it!
    Totally clear, great post John.
    Is there any new language enhacement that is not part of this article?

  • Pablo

    About another enhacement..Lambdas
    Hey, let me please add a link to another post that talks about lambdas.
    I think this is a great enhacement but difficult to understand. This post from Scott simplifies understanding:

    http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx

  • Anonymous

    Great Stuff
    Thanks – that’s a great explanation of the new features

  • Kalidas

    Great Stuff
    Thanks – that’s a great explanation of the new features

  • Kalidas

    Great Stuff
    Thanks – that’s a great explanation of the new features

  • Anonymous

    Excellent
    John,
    Good work, a short and sweet writing.

    Look forward to many more articles over here.

    Sudharsan

  • Anonymous

    Short and Quick to get the latest on 3.5
    Good Work…

  • Anonymous

    damn…!!!!
    u simply rock dude….keep it up!

  • Anonymous

    sqlcache……..

    its nice subject

    Dear Sir
    i want now about the
    sql cache
    in .net3.5

  • Anonymous

    Good Job
    Thanks for your short and sharp explanation and examples.. =)

  • Anil Pandey

    Features
    All these features are realy very exiciting but what are others features of .net 3.5

  • hariharadeep

    About 3.5
    Can you explain 3.5 features that integrates aith sharepoint ?

  • rajivranjan100

    .NET 3.5
    Hi,
    I liked the above information.
    .NET 3.5 rocks.
    If you want some basic information about .NET 3.5
    i would suggest you to visit
    http://www.freejobsreference.com/Interview/NetThreeFive.aspx

  • Anna Kim

    great article!
    I’ve been using .NET 2.0 since 2008. I guess it’s time to learn and use .NET 3.5! Thanks!

  • pradeep kumar ratmele

    ,net
    simple langauge are be must