Srikanth Technologies

What's New In C# 3.0

A new version of C# was released recently along with .NET 3.5. C# version and .NET version were matching till now, but now new version of .NET is 3.5 and C# is only 3.0.

C# 3.0 has got some very interesting new features. I would like to discuss about new features in this blog. As a language, C# 3.0 has gone too far from other languages. The main competitor - Java - has several miles to catch. Well, for Java fans (even I am one of them. I am Sun Certified Java programmer as well), that is my fair opinion.

The following are features of C# 3.0 that I would like to discuss.

Automatically implemented properties

C# now allows you to define properties with a new syntax. In the past one had to create a private variable and then create a property with getter and setter methods. Here is an example for old style of creating a property in C# 2.0.
 public class OldPoint
 {
      private int x,y;
      public int X
      {
            get
            {
                return x;
            }
            set
            {
                x = value;
            }
      }
      public int Y
      {
            get
            {
                return y;
            }
            set
            {
                y = value;
            }
      }
}

Now, let us see how easy it is to create a property in C# 3.0. The following code is to create a class called Point with two properties - X and Y. The underlying variables are automatically created by C#.
 public class Point
 {
      public int X { get; set; }
      public int Y { get; set; }
 }
From outside of the class Point, we can access properties X and Y as we accessed properties in the past. So only the way we create properties changed and not the way we access.

Implicitly Typed Variables

C# allows variables to be declared with keyword var. When you declare a variable with keyword var, you don't specify the type of the variable as c# infers data type for the variable from the expression given to initialize variable. Of course, you must initialize a variable, if you want C# to implicitly take the type of the variable. The following are some of the example of implicitly typed variables.
var i = 43;  // i is taken as int by compiler

var j = i; // j is taken as same type as i

var s = "...This is only a test...";

var numbers = new[] { 4, 9, 16 };

var complex = new SortedDictionary();
complex.Add("Today", DateTime.Now);  // complex is a SortedDictionary where keys are of type string and values DateTime

Implicitly typed variables make huge difference in LINQ - Language Integrated Query, which allows you to give queries using your C# language to access Collections or Arrays, XML documents and Databases.

Object Initializers and Collection Initializers

C# allows you to initialize objects and collections through properties. At the time of creating an object, you can assign values to properties (which assign values to instance variables). It is a short-cut to initializing objects by explicitly calling constructor and properties.

The following example creates an object of Point class and initializes its properties - X and Y - to 10 and 20.

An object of Customer class is created and values are assigned to City and Name properties.

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Customer
{
    public string Name { get; set; }
    public string City { get; set; }
}

public static void Main()
{
     Point p1 = new Point { X= 10, Y = 20};
     List points = new List { new Point { X = 10, Y = 10},
                                            new Point { X = 20, Y = 20} };

     Customer c1 = new Customer { City = "Vizag", Name = "Srikanth" };
}

Extension Methods

An extension method is a method that can extend the functionality of an existing class. Extension methods can be called using objects of a class, even though they are not defined in the class. For users, they seem to be methods of the class, but they are not. In the following example, we create an extension method called compare which is used to compare two Customer objects, even though it is not a method of the Customer class.

This features allows you to add new methods to existing classes without having to modify the code.The only requirement is it has to be a method declared as static in a static class. Its first parameter determines what type of object is to be used to invoke the method. Extension method will never be called if the class itself has (or will have) a method with the same signature.

In many cases, it is recommended to extend the functionality of a class by deriving new class and adding additional method or overriding existing methods.

class ExtensionMethodsDemo
{
    public static void Main()
    {
            Customer c1 = new Customer { Name = "Srikanth", City = "Vizag" };
            Customer c2 = new Customer { Name = "Srikanth", City = "Visakhapatnam" };

            // calls extension method Compare(Customer, Customer) by using c1 and passing c2 as parameter
            if (c1.Compare(c2))
                Console.WriteLine("Same");
            else
                Console.WriteLine("Not same");
        }
}

static class Extensions  // extension methods are placed in a static class
{
    // extension method that is invoked with a Customer object and has a parameter of Customer type
    public static bool Compare(this Customer c1, Customer c2)
    {
       if (c1.Name == c2.Name && c1.City == c2.City)
             return true;
       else
             return false;
    }
}

Anonymous Types

C# allows you to create types on the fly. You can create a new type without any name (anonymous) and create objects of the type there and then.

In the following example, inside the for loop, we created a new anonymous data type with Name and Length properties. Creation of anonymous type, creating an object, assigning values to properties and assigning object to variable details, all are done in one step. Variable details can be used just like any other object and it has two properties - Name and Length.

 public static void Main()
 {
   List names = new List {"Anders","Scott","Mike"};

   foreach (var v in names)
   {
     var details = new { Name = v, Length = v.Length };

     Console.WriteLine(details.Name + "\t" + details.Length);

   }
}

Partial Methods

A partial method is a method that may be defined or not. We have to declare a partial method with keyword partial. Then in the class we may or may not define the partial method. When a partial method is called, C# calls the method if it is defined otherwise call to this method is ignored.

A partial method must return void and should not contain any other modifiers or attributes. However it may be static method.

 partial class PartialMethod
 {
   static partial void Print();  // declaration of partial method
   static partial void AnotherPrint();  // declaration of partial method. It is not defined in the class.

   public static void Main()
   {
       Print();
       Console.WriteLine("In Main");
       AnotherPrint();  // call is ignored as partial method is not implemented

   }
   static partial void Print()  // definition of partial method
   {
        Console.WriteLine("Print Method");
   }
}

Enjoy the new features of C# 3.0. In fact, VB.NET 9.0 has similar features except automatically implemented properties. Of course its syntax is different, sometimes differing by a lot.

Srikanth

Post Your Comment

Image

Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :

Comments