Read, With the Name of Your Lord Who Created

Archive for May 27th, 2008

C# 3.0: Inferred Type Variables, Extension Methods, and Lambda Expressions

Posted by triaslama on May 27, 2008

C# 3.0 brings many of new features. Some of features developed from the existing one (such as lambda expressions that provides more concise syntax than anonymous methods). Other features can be considered as totally new (such as LINQ). In this post together we will learn about Inferred type variables, extension methods, and lambda expressions.

By reading this article I assume that you are familiar with C#, knowing the previous features of this language is a plus.

Inferred Type Variable
Inferred type variable presented through ‘var’ keyword. If you are a Javascript programmer you must be already familiar with ‘var’ keyword. But, ‘var’ in C# 3.0 has different meaning with ‘var’ keyword in Javascript. In C# 3.0 when we use ‘var’, we tell the compiler that the type of variable should be inferred from the assignment. In Javascript var means that a variable can hold any kind of type.
Consider the following Javascript file:

    var myVariable = 5;
    window.alert(myVariable);
    myVariable = “I change the type of myVariable, now myVariable is a string!”;
    window.alert(myVariable);

 

At the beginning I assign myVariable with 5 (an integer), but later, I assign myVariable with a string (so myVariable can hold any kind of value). But its not the case with ‘var’ in C# 3.0.

using System;

class InferredTypeVar
{
   static void Main()
   {
      var myVariable = 12.5;
      Console.WriteLine("myVariable: "+myVariable);
   }
}

 

Because I assign 12.5 to myVariable then type of myVariable will be double. If we try to fake the compiler and add the following code (hoping that it will the same as in Javascript):

Read the rest of this entry »

Posted in C# | Tagged: , , , | 5 Comments »