Start using new C# 3.0 language features in 5 minutes

[tag]Visual Studio 2008[/tag] and [tag]C# 3.0[/tag] are coming with lots of new features, new language constructs, etc. That’s all super but it takes some time to get into it. However, there are some cool stuff you can start using in 5 minutes and I’ll just put a list here with just really basic examples.

var keyword (implicitly typed local variables)
This one is easy: var is a new keyword, when used compiler infers the type of the variable from the expression:

var x = 1;
var y = "some text";
var someVariable = myRepository.GetSomeObjects();

In Visual Studio, if you hover over someVariable you will instantly get what is the type of it, you get full intellisense support etc. The benefit of using var keyword is more concise code, better readability, better communication of ideas. Just imagine some super complicated type declaration as

Dictionary<CustomCompositeKey<string, int>,List<CustomGeneric<string>>>

So which one is better:

Dictionary<CustomCompositeKey<string, int>, List<CustomGeneric<string>>>
           userData = myRepository.GetUserData();
- or -
var userData = myRepository.GetUserData();

You can use var only in method body, you cannot use it in class definition. Also keep in mind that var does not stand for any type, it is just shorthand for the real type, so the following yields compilation error:

var myInteger = 1;
myInteger = "text"; // this will give compilation error, since myInteger is int

Lambda Expressions
Lets say [tag]lambda expressions[/tag] are shorthand for anonymous delegates. There’s more to it but this will suffice for now. Look at this example:

List<string> listOfStrings = new List<string>(
        new string[] { "One", "Two", "Three", "Four" });
string found1 = listOfStrings.Find(delegate(string item) { return item == "One"; });
string found2 = listOfStrings.Find(delegate(string item) { return item == "Two"; });

We are using anonymous delegates to find specific strings. If we would use lambda expressions instead it would look like this:

List<string> listOfStrings = new List<string>(
            new string[] { "One", "Two", "Three", "Four" });
string found1 = listOfStrings.Find(item => item == "One");
string found2 = listOfStrings.Find(item => item == "Two");

I find this simply more concise and better communicating without unnecessary cluttering information. Mind thought that the example is really really simple but if you use anonymous delegates a lot you will get instant benefits even for simplest code.

Lambda expression has => operator to designate it as lambda expression, on the left you have parameters that are required by the delegate, in our particular case it was of type: Predicate<string>, and on the right you have expression so to compare it look at this table:

anonymous delegate lambda expression
delegate(string item) item
{ return item == "Test";}
item == “Test”

We don’t need delegate keyword, this => can be seen as shorthand  for that, we don’t need to specify it’s string since we are operating on string so compiler knows how to infer the right type, at the end there is no return keyword the result of the expression after => is returned. If you have more then one input parameter you can use something like this: (a,b) => a == 1 && b == 2 for example.

Extension methods
[tag]Extension methods[/tag] are another nice and easy to use feature. Extension methods are enabling us to add additional functionality to already existing objects (possibly CLR types) without sub-classing it or changing original code of the type. Syntax looks like this:

namespace MyNamespace{
     public static class MyExtensions  {
         public static string SayHelloToMe(this string name)
                    {return "Hello " + name;}

What this does is actually “adding” a new method – SayHelloToMe to the string class, extends it. So now I can use it like this:

using MyNamespace; //where extension method is defined
Debug.Assert("Mihailo".SayHelloToMe() == "Hello Mihailo");
//you can even execute extension method on null value
string x = null;
Debug.Assert(x.SayHelloToMe() == "Hello ");

In order to create extension method we have to define a static method in a static class and add keyword this in front of  the parameter of the type that we want to extend (this string name – in the above example). Note that in the example above there is no need to pass name parameter to the SayHelloToMe method since the object itself is used (so another shorthand: “Mihailo”.SayHelloToMe() is equivalent to MyNamespace.MyExtensions.SayHelloToMe(“Mihailo”)) . Mind that in extension methods you cannot access private or protected properties of the type being extended.

Above, Hello World like, example is just to show how to define and use extension methods, you can probably think of something more useful. For example I found it useful for extending membership classes. You could have something like this:

MembershipUser user = Membership.GetUser();
BusinessUser businessUser = user.GetBusinessUser();

Where GetBusinessUser is extension method:

public static BusinessUser GetBusinessUser(this MembershipUser user){...}

In 5 minutes I briefly covered: var keyword, lambda expressions and extension methods. As you have seen, they are easy to use and are helping us keep our code a bit simpler, neater and more natural. Enjoy.

You can download Visual Studio 2008 (trial, or free express version) from here.

  1. #1 by Andy B on January 16, 2008 - 11:15 am

    I’m not convinced about the var type. Could it be the start of a slippery slope back to the equivalent of the variant as existed in good old VB? Don’t forget that aliasing exists already so, if we take the example of the type used here (Dictionary,List>>) you can do the following (assuming the types CustomCompositeKey and CustomGeneric reside in namespace MyNS):

    using MyDictionary = System.Collections.Generic.Dictionary, System.Collections.Generic.List>>;

    This enables you to use:

    MyDictionary userData = myRepository.GetUserData();

  2. #2 by Andy B on January 16, 2008 - 11:18 am

    Oh dear, the angled brackets seem not to have quite come out right in my previous post. Maybe I shoud have used < but I’m sure you get the idea. ;-).

  3. #3 by Mihailo Lalevic on January 16, 2008 - 11:45 am

    Hi Andy B,
    Thanks for comments, I got the idea, no bother 😉
    I see what you mean, however var is not a type it just instructs compiler to infer type from the expression see following cases:
    var x = 1; // x is int even though var keyword is used
    var y = “Test”; //y is string and it can’t be assigned anything else later on but string
    y = 5; // compiler error!
    y = “Test2”; //everything’s fine
    Difference then vb would be that var is not variant it is the type of the expression on the right. Mind that you will get compiler error rather then runtime error if you try to assign value of a wrong type to it as in example.
    As for aliases: yes, they are shorthand as well but again for different types you have to define different aliases and you have to do it in all files you wanna use them, by using var well you just use var for anything 🙂

    I hope this helps a bit in persuading you to adopt new features 😉


  4. #4 by wow account on October 26, 2010 - 3:07 am

    I think the new features look good but isn’t an Object Initializer already present in the language in the form of a constructor?

    Is there a slight danger that some of the “syntactic sugar” being generated will confuse the issue and lead to the same job being done in a multitude of different ways?

    All the LINQ stuff is excellent but a few new features look like they might be generated by developers with not enought to do on a Wednesday afternoon 🙂

  5. #5 by franky T on April 7, 2011 - 6:35 am

    hey great blog here im going to bookmark you so i can get back to these and apply them during work cant wait thank you

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: