Tuesday, May 25, 2010

Lambda Expression in C# .Net

Lambda expression is a new way to defines an anonymous function. That function can take arguments (if any) & can return a value from the function.

“=>” (read as ‘goes to’) is the operator to define the lambda expression. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.

Consider the following e.g.

class Program

    {

        /// <summary>

        /// Declare a delegate

        /// </summary>

        /// <param name="i">Input parameter</param>

        /// <returns>Result</returns>

        delegate int myDelegate(int i);

 

        public static int Square(int i)

        {

            return i * i;

        }

 

        public static void Main()

        {

            int input = 11;

            myDelegate del = Square;

            int result = del(input);

 

            Console.WriteLine("Result : " + result);

            Console.ReadLine();

        }

    }

Here I defined a delegate & a function to calculate the ‘Square’ of the input number. I can rewrite the same code using lambda expression which is as follows

    class Program

    {

        /// <summary>

        /// Declare a delegate

        /// </summary>

        /// <param name="i">Input parameter</param>

        /// <returns>Result</returns>

        delegate int myDelegate(int i);

 

        public static void Main()

        {

            myDelegate del = myInput => myInput * myInput;

            int result = del(input);

 

            int input = 11;

            Console.WriteLine("Result : " + result);

            Console.ReadLine();

        }

    }

 

Basically myInput => myInput * myInput; expression defines an anonymous method which takes ‘myInput’ as input, does multiplication & returns the output (int).

 

 

  • We can have multiple input parameters in an lambda expression

(x, y) => x * y

  • We can explicitly declare the variable type in the input parameters. if no data type is given then compiler would infer its type.

(int x, int y) => x * y

  • Use empty parentheses if there are no arguments to be passed to the method.

() => MyMethod()

  • Use { } if your function has multiple statements

myInput =>

            {

                myInput = myInput + 10;

                myInput = myInput + 20;

            };

 

We can use standard Func<> delegate with lambda expression. The same code can be written as

class Program

    {

        public static void Main()

        {

 

            Func<int, int> del = i => i * i;

            int result = del(10);

            Console.WriteLine("Result : " + result);

 

            Console.ReadLine();

        }

    }

Lambda expression is mainly meant for using it LINQ.

Monday, May 24, 2010

Type Inference ( Implicitly typed variables)

To define any variable we have to tell the data type which declaring it. For e.g

string str = "Hello World";

This tells the compiler that str is of type string.

Microsoft has introduced new keyword “var” in.Net 3.5. This is similar to var in java script.  When any variable is declared as var then complier decides its data type at compile type based on the value assigned to that variable. This is known as type reference. For e.g.

image

You can see that it has detected str as string & allowing us to call all string functions.

Let’s take few more examples to under type inference

            var name = "Atul";

            var age = 26;

            var prog = new Program();

            Console.WriteLine("Name is of type " + name.GetType().Name);

            Console.WriteLine("Answer is of type " + age.GetType().Name);

            Console.WriteLine("Prog is of type " + prog.GetType().Name);

 

Output would be

image

Implicit type inference rules

1.  Variable need to initialize it while declaring it. For e.g. following code would not compile

 

// This would not compile

 var name;

 

2.       Initialization to null value is not allowed

        

// This would not compile

var name = null;

 

3.  Conditional operator can be used during initialization time for e.g.

 

            bool myCondition = false;

            var name = myCondition ? "a":"b";

 

4.  If conditional operator is used with initialization then the data type of if/else must be same. Following code would not work. Compiler would not be able to decide the data type of ‘name’

 

            // This would not compile

            bool myCondition = false;

            var name = myCondition ? "a": false;

 

5.  Type inference works with subtyping as well. For e.g.

 

class MyBase

{

}

 

class MyDerive : MyBase

{

}

 

bool myCondition = true;

         var myObj = myCondition ? new MyBase() : new MyDerive();

Console.WriteLine(myObj.GetType());

 

Output

image

6.       We can also use type inference with Arrays

 

// This will declare an array of type int32

var myArray = new []{1,2,3,4};

 

This will define an array integers.

Conclusion : Type inference is a nice feature where you do not have to explicitly mention the data type while declaring the variable. However it is not recommended to use ‘var’ keyword if you know the type. Basically new keyword is introduced to support LINQ where we don’t know the result type of the query.

Auto Implemented Properties – C# 3.0+

Technorati Tags: ,

Auto Implemented feature allows you to define the properties in more concise way. You need not to explicitly declare a variable & create a property for it. Complier internally declares a variable & generates code to access that variable though the property.

 Old Style of defining the properties

class Emp

    {

        // Variable/fields

        int salary;

        string name;

 

        /// <summary>

        /// Property to access salary field

        /// </summary>

        public int Salary

        {

            get { return salary; }

            set { salary = value; }

        }

 

        /// <summary>

        /// Property to access name field

        /// </summary>

        public string Name

        {

            get { return name; }

            set { name = value; }

        }

    }

New way of defining properties

Following is new way to use properties. From functionality point of view both are same. We need not to declare a variable, complier would do it internally.

    class Emp

    {

        /// <summary>

        /// Property

        /// </summary>

        public int Salary { get; set; }

 

        /// <summary>

        /// Property

        /// </summary>

        public string Name { get; set; }

    }

 

Notes

1. There is no different in term of performance in both the approaches.

2. Second approach is a concise way, code is more readable/maintainable.

3. We can use different accessor level in getter & setter, for e.g.

   

       public string Name { get; private set; }

 

4. Auto implemented must have both getter & setter field. For e.g. following code would not work

 

        // This would not compile

        public int Salary { set; }

 

5. To make read only property, setter can be declared as private. However both getter & setter can not be read only.

 

        // Read only property

        public string Name { get;  private set; }

 

        // Write only property

        public string Name { private get;  set; }

 

        // This would not compile

        public string Name { private get;  private set; }

Extension Methods - .Net 3.0 or later

1.       Extension method allows you to add new method to a class without modifying the existing class. We can add new method to a sealed class well. 

2.       Extension method is special kind of static methods. The first parameter specifies which type the method operates on. Also the parameter is preceded by “this” modifier. We cannot use the ‘this’ keyword in a normal static method. But to define the extension method we have to use ‘this’ key word with the first parameter of that method. For e.g. ‘string’ does not have any in build method to reverse the string. Now let’s say we want to add a new method to reverse the string. 

    public static class MyExtensionMethodClass

    {

        /// <summary>

        /// This is a extension method to reverse the string

        /// </summary>

        /// <param name="input">Input string to revese</param>

        /// <returns>Reversed string</returns>

        public static string Reverse(this string input)

        {           

            int length = input.Length;

            StringBuilder inputString = new StringBuilder(input);

 

            for (int index = 0; index < length / 2; index++)

            {

                char character = inputString[index];

                inputString[index] = inputString[length - index - 1];

                inputString[length - index - 1] = character;

            }

 

            return inputString.ToString();

        }

    }

 

Now when you ‘string’ class it would show you a new method as shown below.

image 

3.       Extension method is like a visitor pattern which allows you to change class structure without changing the actual class. You can alter the structure without changing the logic.

4. Extension method cannot be used to override the original method. If there is already a method with same name & signature as extension method then the original method would be called rather than the extension method. This is because it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds

          An extension method will never be called if it has the same signature as a method defined in the type. For e.g.

    class Program

     {

         static void Main(string[] args)

         {

             MyClass obj = new MyClass();

             obj.MyFun();

 

             Console.ReadKey();

         }

     }

 

     public static class MyExtensionMethodClass

     {

         public static void MyFun(this MyClass obj)

         {

             Console.WriteLine("Inside Extension method");

         }

     }

 

     public class MyClass

     {

         public void MyFun()

         {

             Console.WriteLine("Inside class MyClass.MyFun");

        }

     }

/*

Output :-

Inside class MyClass.MyFun

*/