Click here to Skip to main content
15,905,785 members
Articles / Web Development / ASP.NET

C# 3.0 New Language Features (Part 1)

Rate me:
Please Sign up or sign in to vote.
4.67/5 (42 votes)
4 Jan 2008CPOL3 min read 78.4K   62   12
An article about the new language features of C# 3.0


Well, in this article I'll illustrate some of the C# 3.0 new language and compiler features and I'll illustrate the rest of the features in the second part. First of all, let's define all the new features:

  1. Implicitly Typed Local Variables and Arrays
  2. Object Initializers
  3. Collection Initializers
  4. Extension Methods
  5. Anonymous Types
  6. Lambda Expressions
  7. Query Keywords
  8. Auto-Implemented Properties
  9. Partial Method Definitions

In this article, I will define the first four features with code samples to make it clear.

Implicitly Typed Local Variables and Arrays

Instead of using the explicit type, now we can use the inferred type which means declaring any local variable as var and the type will be inferred by the compiler from the expression on the right side of the initialization statement.
This inferred type could be:

  • Built-in type
  • Anonymous type (will be discussed later)
  • User-defined type
  • Type defined in the .NET Framework class library

Now let's see how local variables can be declared with var:

var int_variable = 6;                 // int_variable is compiled as an int
var string_variable = "Mony";         // string_variable is compiled as a string
var int_array = new[] { 0, 1, 2 };    // int_array is compiled as int[]

// Query is compiled as IEnumerable<customer />
var Query =
    from c in customers
    where c.Name == "Mony"
    select c;

// anonymous_variable is compiled as an anonymous type
var anonymous_variable = new { Name = <int />
var list = new List<int />"Mony", Job = "Web Developer" };

// Implicitly Typed Arrays
 var int_array = new[] { 1, 10, 100, 1000 }; // int[]
 var string_array = new[] { "hello", null, "world" }; // string[]

Restrictions when using implicitly-typed variables are as follows :

  • var can only be used when you are to declare and initialize the local variable in the same statement.
  • The variable cannot be initialized to null.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression. In other words, var i = i++; produces a compile-time error.
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then you will get a compile-time error if you try to initialize a local variable with the var keyword.

Object Initializers

Sometimes you spend a lot of time writing a lot of redundant code to declare constructors that do the same job. Object initializers can be used to initialize types without writing explicit constructors.

Code Example 1

private class Person
    // Auto-implemented properties
    public int Age { get; set; }
    public string Name { get; set; }

static void Test()
    // Object initializer
    Person per = new Person { Age = 22, Name = "Mony" };

Code Example 2

class Point
    int x, y;
    public int X
        get { return x; }
        set { x = value; }
    public int Y
        get { return y; }
        set { y = value; }

When you instantiate this class, you normally write the following code:

Point p = new Point();
p.X = 10;
p.Y = 20;

Instead, you can create and initialize a Point object like this:

Point p = new Point { X = 10, Y = 20 }; // object initializer

Or even like this:

var p = new Point { X = 10, Y = 20 }; // object initializer

With complex fields, such as a square or a rectangle whose corners are located at the points p1 and p2, you can create the Rectangle class as follows:

public class Rectangle
    Point p1;
    Point p2;
    public Point ULcorner { get { return p1; } set { p1 = value; } }
    public Point LRcorner { get { return p2; } set { p2 = value; } }

You can create and initialize the Rectangle object like this:

var rectangle = new Rectangle { ULcorner = new Point { X = 0, Y = 0 },
            LRcorner = new Point { X = 10, Y = 20 } };

Collection Initializers

Enables initialization of collections with an initialization list rather than specific calls to Add or another method. This initialization has the same effect as using the Add method with each collection element.

public class Person
   string _Name;
   List _Intersets = new List();
   public string Name { get { return _Name; } set { _Name =value; } }
   public List Interests { get { return _Intersets; } }

class Test
   static void Main(string[] args)
    List<person /> PersonList = new List<person />();
    Person p1 = new Person();
    p1.Name = "Mony Hamza";
    Person p2 = new Person();
    p2.Name = "John Luke";

In C# 3.0, you can write less code to express the same concept:

static void Main(string[] args)
    var PersonList = new List<person />{
    new Person{ Name = "Mony Hamza", Interests = { "Reading", "Running" } },
    new Person { Name = "John Luke", Interests = { "Swimming"} };

Extension Methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

To create an extension method, declare it as a static method in a static class. The first parameter of an extension method must be the keyword this.

The following is an example of an extension method to convert the temperature from Fahrenheit to Celsius.

namespace MyNameSpace
     public static class MyClass
           public static double ConvertToCelsius(this double fahrenheit)
              return ((fahrenheit – 32) / 1.8); }


Now it is possible to invoke the extension method, ConvertToCelsius, as if it is an instance method:

double fahrenheit = 98.7;
double Celsius = fahrenheit.ConvertToCelsius();

So it adds a method called ConvertToCelisius to an existing type which is double here.

Hope this simple article makes the C# 3.0 new language features quite clear. In the next article, I'll discuss the other five features.

Waiting for your feedback.


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

Written By
Web Developer
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

GeneralMy vote of 4 Pin
S@53K^S13-Jul-10 17:31
S@53K^S13-Jul-10 17:31 
GeneralNicely explained. Pin
burning_sky3703-Dec-09 21:21
burning_sky3703-Dec-09 21:21 
General;} Pin
radioman.lt24-Mar-09 22:46
radioman.lt24-Mar-09 22:46 
GeneralCongrats and corrections [modified] Pin
Tiago Freitas Leal24-Jul-08 22:07
professionalTiago Freitas Leal24-Jul-08 22:07 
First of all, congratulations for a simple yet comprehensive review of C# 3 new features.

Next some small corrections

1. Typo: _Intersets instead of _Interests

List _Intersets = new List();
won't compile. It should be
List<string> _Intersets = new List<string>();

I guess HTML wash out your "<string>" (it happened the same to me a few seconds ago)

modified on Friday, July 25, 2008 4:15 AM

Generalwatch out for plagiarism Pin
saeed.darya7-Mar-08 18:43
saeed.darya7-Mar-08 18:43 
GeneralNice Pin
Reza Shams Amiri17-Jan-08 6:20
Reza Shams Amiri17-Jan-08 6:20 
GeneralGood Job Pin
saunde9-Jan-08 7:33
saunde9-Jan-08 7:33 
JokeWaiting... Pin
blacer9-Jan-08 2:31
blacer9-Jan-08 2:31 
GeneralWay to go Pin
Abdelrahman Khalil8-Jan-08 2:08
Abdelrahman Khalil8-Jan-08 2:08 
GeneralBenifits Pin
ryanoc3337-Jan-08 2:32
ryanoc3337-Jan-08 2:32 
GeneralWell explained Pin
Jcmorin5-Jan-08 8:28
Jcmorin5-Jan-08 8:28 
Generalnice & simple Pin
napo@burgasnet.com5-Jan-08 3:42
napo@burgasnet.com5-Jan-08 3:42 

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.