Click here to Skip to main content
Click here to Skip to main content

New features of C# 3.0

, 4 Apr 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
A quick look at C# 3.0 language features.

Introduction

In this article I am demonstrating the new features in C# 3.0. This demo is created as a simple C# console application to understand the new features of C# 3.0.

Background

I am a regular participant of Microsoft web casts and developer conferences. These web casts  gives me a better understanding of new technologies. Also I was able to implement all these successfully in my projects. This article helps you understanding what are the new language features of C# 3.0

Using the code

Ok... Here we go…

If you don't have licenced Visual Studio 2008 installed on your machine, I would suggest you to download and inslall Visual Studio 2008 Express Edition ( Free).  

This sample demo application starts with creating an Employee class. This has few properties in it.  I would suggest you start doing it while going through this article.

public class Employees
{ 
  #region AUTO IMPLEMENTED PROPERTIES 
  //C# 3.0 - Auto implemented properties. 
  public string EmployeeName { get; set; } 
  public int EmployeeID { get; set; } 
  public string Department { get; set; } 
  #endregion 
}      

Here I have inroduced a language feature called Auto Implemented properies. You can notice that there is no private fields been declared for these properties. The compiler will creates the private backing fields for you.

Now we have created our Employee class. Lets create our main Program class now.

public class Program 
{ 
  static void Main(string[] args) 
  { 
    List<Employees> employees = LoadEmployees();
  } 
}   

In the program main method, I have declared a List of Employees. I am using the method LoadEmployees to get the Employee list. Normally in C#2.0 we will use the following code to create an Employee object and will add to the List.

// In C# 2.0 
private static List<employees /> LoadEmployees() 
{ 
  Employees emp1 = new Employees();
}  

Here we need to set the values to the properies using the Employee objects emp1. ie For example emp1.EmployeeName = "Albert"; Finally we will add the employee objects to an Employee List.

Now we will see the magic of C# 3.0


CSharp3

  private static List<Employees> LoadEmployees()
  {     
    // C# 3.0 Collection Initializers
    List<Employees> employees = new List<Employees>()
    {
     // C# 3.0 Object Initializers.
     new Employees{ EmployeeName="Albert", EmployeeID=1234, 
     Department="Software Testing"},
     new Employees{EmployeeName="Justin", EmployeeID=1234, 
     Department="Development"}
    }; 
  }

Here I have introduced a new language feature called Object Initializers and Collection Initializers.

One more change…

Please note this line

 List<Employees> employees = new List<Employees>() { ....

You can see the repetition of List<Employees>. The type of List<Employees> is mentioned twise. Lets see how can we avoid this in C# 3.0

I am rewriring the above line as

var employees = new List<Employees>() {  .... 

 Ohh..whats that!..This is called Local variable Type Inference.

Don’t worry it will not break our type safety. You cannot assign any other types to employees as the compiler strongly typed the employees as the type assigned in its right side.

 Ok…Now we can see different ways of querying this list of Employees using the LINQ feature of C# 3.0 We will go back to or Main method.

# 1.

static void Main(string[] args)
{
  List<Employees> employees = LoadEmployees();
 // C# 3.0 Lambda Expressions -- Where is an Extension method of   Enumerable class
   var results = Enumerable.Where(employees, e => e.Department == "Development");
}

C# 3.0 introduced a new class called Enumerable with some methods. This can be used on any IEnumerable types. Here I am using a method called Where. This method filters the collection by using some predicates. This predicates are created inline using another language feature known as “Lambda Expressions”. This simplifies the syntax of anonymous methods which we used in C# 2.0. This returns a list of Employees whose department is  “Development”.

 # 2

The Where method can be used as an extension method on the employees object. Yet another feature of C# 3.0 which we will cover later in this article.

static void Main(string[] args)
{
  List<Employees> employees = LoadEmployees();
 // C# 3.0 Lambda Expressions -- Where is an Extension method of   Enumerable class
 var results = employees.Where(e => e.Department == "Development");
}

# 3.

One more improvement on this. Ie called a query expressions. I am re-writing the above code as

static void Main(string[] args)
{
  List<Employees> employees = LoadEmployees();
  var query = from e in employees
              where
              e.Department == "Development"
              select e;
} 

I am not covering all the capabilities of LINQ here. We can use this query expressions to query against databases, XMLs, objects or any types of data that a third party can extend to work with LINQ. Lets try to print this result in a console.

foreach (var item in query)
{
Console.WriteLine("{0},{1},{2}", item.EmployeeName, item.EmployeeID, 
item.Department);
}

Finally… we will see another feature called Extension Methods

Ok..What is Extension methods?

Extension methods are static method that can be invoked using the instance method syntax.

How can add an extension method?

namespace ExtensionMethodDemos
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    public static class SampleStringExtensionClass
    {
        public static string SayHello(this string s)
        {
            return "Hello" + s;
        }
    }
}

Here I have a static class which has static method named SayHello.

Extension methods are defined as static methods but are called by using instance method syntax.

Note that the parameter to the extension method that is prefixed with the "this" keyword - this tells the compiler which type we are "extending" with our extension method.

Ok.. Let see how we can use in our code. I will take the same main program we used above.

namespace CSharp3._0Features
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using ExtensionMethodDemos;  
    public class Program
    {
        static void Main(string[] args)
        {          
            string sampleString = " Albert";
            string strExtended = sampleString.SayHello();
            Console.WriteLine();
            Console.WriteLine("****EXTENSION METHODS*******"); 
            Console.WriteLine(strExtended); 
            Console.ReadLine();
        }      
    }
}

Note that I have used the namespace ExtensionMethodDemos whch we created earlier. I have created a variable of string type. This new string type is now having the method “SayHello()” as its extension method.

Points to Remember

If you do implement extension methods for a given type, remember the following two points:

  • An extension method will never be called if it has the same signature as a method defined in the type.
  • Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive.

Reference: Microsoft MSDN, Microsoft MSDN WebCasts.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

P S Sreejith
Software Developer (Senior) Ness Technologies
India India
No Biography provided

Comments and Discussions

 
GeneralVery nice! PinmemberLord TaGoH4-Apr-09 11:32 
GeneralRe: Very nice! PinmemberP S Sreejith5-Apr-09 19:50 
GeneralMy vote of 1 PinmemberJon Artus3-Apr-09 5:21 
GeneralMy vote of 2 Pinmembercip2kro3-Apr-09 3:38 
GeneralMy vote of 2 Pinmemberf r i s c h3-Apr-09 2:27 
GeneralGood entry level article [modified] Pinmembercreativekid13-Apr-09 0:00 
GeneralMy vote of 1 PinmemberGriffinPeter2-Apr-09 11:39 
GeneralRe: My vote of 1 PinmemberP S Sreejith4-Apr-09 5:05 
GeneralMy vote of 1 PinmemberGoran Mitrovic2-Apr-09 8:45 
GeneralThanks Pinmemberthund3rstruck2-Apr-09 6:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 4 Apr 2009
Article Copyright 2009 by P S Sreejith
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid