Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#

New features of C# 3.0

Rate me:
Please Sign up or sign in to vote.
2.96/5 (13 votes)
4 Apr 2009CPOL4 min read 35.7K   94   7   15
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.

C#
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.

C#
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.

C#
// 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

C#
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

C#
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

C#
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.

C#
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.

C#
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

C#
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.

C#
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?

C#
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.

C#
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)


Written By
Software Developer (Senior) Ness Technologies
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralVery nice! Pin
Lord TaGoH4-Apr-09 10:32
Lord TaGoH4-Apr-09 10:32 
GeneralRe: Very nice! Pin
P S Sreejith5-Apr-09 18:50
P S Sreejith5-Apr-09 18:50 
GeneralMy vote of 1 Pin
Jon Artus3-Apr-09 4:21
Jon Artus3-Apr-09 4:21 
GeneralMy vote of 2 Pin
cip2kro3-Apr-09 2:38
cip2kro3-Apr-09 2:38 
GeneralMy vote of 2 Pin
f r i s c h3-Apr-09 1:27
f r i s c h3-Apr-09 1:27 
GeneralGood entry level article [modified] Pin
creativekid12-Apr-09 23:00
creativekid12-Apr-09 23:00 
Let this be one other article for starting with C# 3.0.

modified on Friday, April 3, 2009 5:09 AM

GeneralMy vote of 1 Pin
CARPETBURNER2-Apr-09 10:39
CARPETBURNER2-Apr-09 10:39 
GeneralRe: My vote of 1 Pin
P S Sreejith4-Apr-09 4:05
P S Sreejith4-Apr-09 4:05 
GeneralMy vote of 1 Pin
Goran Mitrovic2-Apr-09 7:45
Goran Mitrovic2-Apr-09 7:45 
GeneralThanks Pin
thund3rstruck2-Apr-09 5:01
thund3rstruck2-Apr-09 5:01 
GeneralMy vote of 2 Pin
Jay Riggs2-Apr-09 4:51
Jay Riggs2-Apr-09 4:51 
GeneralZzzzzzzzzzzzzzzz Pin
PIEBALDconsult2-Apr-09 4:44
mvePIEBALDconsult2-Apr-09 4:44 
GeneralNice article to get someone started. Pin
MAHESHSETHI2-Apr-09 2:27
MAHESHSETHI2-Apr-09 2:27 
GeneralRe: Nice article to get someone started. Pin
JCrane23-Apr-09 1:31
JCrane23-Apr-09 1:31 
GeneralRe: Nice article to get someone started. Pin
P S Sreejith4-Apr-09 4:06
P S Sreejith4-Apr-09 4:06 

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

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