Friday, January 25, 2013

Lambda Expression, Statement Lambda, Action Delegate, Func Delegate, Differences Between Action and Func and Instantiating Delegates with Lambda

Continuing from last page:
Lambda expressions or statement lamda can be passed where a delegate is expected.

Lamda expressions may or may not expect input parameters and have an expression to right of lambda that may evaluate to a return value.

      Func<int, int, int, int, int> hello = (a, b, c, d) => a + b + c + d;

   here a,b,c,d are input parameters and return type is int which is result of e
xpression (a+b+c+d). 

In above lambda expression is assigned to Func delegate which accepts 4 input parameters of type 'int' and return type is 'int' again.


We have to make sure, lambda expressions input is convertible to delegate's input type & return of lambda is convertible to delegate's return type.



In above case (a+b+c+d) will be of type of int which is same of Func<int,int,int,int,int TResult> delegate's return type i.e. int.



Lambda expression can also contain statements to right of lamda that might not return any value.


           Action<int> mm = (a) => Console.WriteLine("EEE");
      mm(5);

In above example right side of expression does not evaluate to anything though it accepts a parameter 'a'. This is assigned to default Action<int> delegate which does not expect any return type, but has an input parameter of type 'int'.


Now let us see what is a statement lambda. Statement lambda is similar to lambda expression but statement(s)/expression to the right of lambda is enclosed in {} braces.
They can contain multiple statement since they are enclosed in braces. Braces also indicate scope /block of lambda statement. 


                Action<int> actw = (a) => 
            {
                string s = "square = " + a * a;
                s = s + " - new";
                Console.WriteLine(s); 
            }

Here we are assigning statement lambda to a delegate that has single input parameter of type int. We are not returning anything from lambda but redirecting the square of number to console.


We use lambda and anonymous methods only in simple scenarios where a set of simple statements can be passed in method, instead of having dedicated method of handling or instantiating delegate.
In below example, I'm invoking a delegate and assigning a statement lambda for callback. Here having a callback method that would just print completion status would not make much sense and hence I replaced it with a lambda expression which outputs the delegate's method execution status in the callback.
Here AsyncCallback expects a method that accepts IAsyncResult parameter and return type is void. Our statement lambda accepts this IAsyncResult  as input and returns nothing and hence can be passed in as method that is expected by AsyncCallback.


        public static void ExecuteDelegate(Func<int, int, int, int, int> hello)
        {
                hello.BeginInvoke(2, 3, 4, 5,                
                   new AsyncCallback((asyncresult) => {  
                          Console.WriteLine("Completed = " +  
                                    asyncresult.IsCompleted); }),                
                                  null);
        }


Till now I have only use Func<> and Action<> delegates but lambda can be used for any delegate of matching return and input types. Func and Action are the delegates provided by default by the framework to avoid overhead of writing our own delegates for general cases. These delegates are generic they are extended to accept 0, 1, 2, 3 or more parameters. Number of input parameters that are accepted by both delegates was 0 to 4 in .NET 3.5.


Main difference between Action delegate and Func delegate is,


Action - delegate that does not have return value and accepts up-to four input parameters. (.NET 3.5)
Action also can encapsulate a method that take no input and no return value. 

Types:
Action
Action<in T1> - in represents input parameter.
Action<in T1,in T2>
Action<in T1,in T2,in T3>
Action<in T1,in T2,in T3,in T4>

Func<TResult> - Func delegate is used when we have a return value but input parameter list is optional. Func delegate can encapsulate method that returns a value and accepts no input. Func can encapsulate methods that have 0 - 4 in put parameters and return a value. Last value in parameter list represents the return type.

Func<TResult> - TResult represrents return type.
Func<in T1, out TResult> 
...............


delegate void PrintCharsDelegate(string s);


PrintCharsDelegate del = (s) =>
                   {
                       Console.WriteLine("Encryted String for {0} = ", s);
                              foreach (char ch in s)
                              {                                                   
                                                   Console.Write((char)((int)ch+1));
                              }
                   };
del("Hello");



Here statement lambda which encrypts the given string, is assigned to delegate which accepts string and returns nothing.

Anonymous methods are very similar to statement lambdas. They can be used to instantiate delegates just like statement lambda. We will see them in another article




Wednesday, January 23, 2013

Anonymous Methods, Lambda Expressions, lamda vs anonymous and their advantages

Anonymous methods:


Anonymous methods are introduced in .NET 2.0. Anonymous methods are inline methods with no name that can be directly assigned to a delegate. These methods are set of statements without any special syntax as in lambda expressions.

Advantages of anonymous methods over lambda are:

 They can be assigned/converted to delegate of any signature. They do no need parameter list to be mentioned like in lambda expressions.

Examples:

 Example 1.a

button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };
Example 1.b
delegate int Square(int k);
Square d = new delegate(int k){return k*k;};

Common for Both Lambda and Anonymous methods:

  1. We avoid overhead of writing methods for handlers or delegate by using anonymous methods whenever possible. 
  2. They can't be explicitly called in code. 
  3. They can't contain goto or break or continue statements where the target is out of expression or method block.
  4.  Scope of variables in anonymous methods is method block only.
  5.  They can't accept parameters using ref or out keyword.
  6.  They can use variable declared outside their scope and such variable are called outer variables.

Lambda Expressions:


Lambda expressions are introduced in C# 3.0. They are used to instantiate a delegate by an inline method. This inline method will contain lambda (=>) after the input parameter list and statement to the right of lambda symbol. 

(input parameters) => expression

By using lambda expressions we can write local methods that can be passed as arguments that expect delegate as an argument.
    
     (x) => x? 5:0;

  () => SomeMethod() //zero parameters

Here, x is the input parameter. 

Statement lambda is similar to lambda expressions where in set of statements to the right of lambda are enclosed in {} and parameter list is to the left of lambda operator. 

      (input parameters) => {statement;}

Lambda expression can only be used to instantiate delegate of particular signature.

The general rules for lambdas are as follows:

  • The lambda must contain the same number of parameters as the delegate type.
  • Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.
  • The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.







Sunday, January 6, 2013

Abstract Class vs Interfaces (C#) - Differences, Recommendations about when to use what?

This is a favorite question of any interviewer. Probabilities are less where interviewer expects syntactic differences rather one might be looking at design level differences. Next question which follows is "When do you prefer interface over abstract classes" or other way round. I have collected answers over the internet to compile one simple page to answer this question.

Below is from John Noah's interview questions comiplation:


An abstract class can provide complete, default
code and/or just the details that have to be
overridden.

An interface cannot provide any code at all,just
the signature.

In case of abstract class, a class may extend
only one abstract class.

A Class may implement several interfaces.

An abstract class can have non-abstract
methods.

All methods of an Interface are abstract.

An abstract class can have instance variables.
An Interface cannot have instance variables.

An abstract class can have any visibility:
public, private, protected.

An Interface visibility must be public (or)
none.

If we add a new method to an abstract class
then we have the option of providing default
implementation and therefore all the existing
code might work properly.

If we add a new method to an Interface then
we have to track down all the implementations
of the interface and define implementation for
the new method.

An abstract class can contain constructors .
An Interface cannot contain constructors .

Abstract classes are fast.

Interfaces are slow as it requires extra
indirection to find corresponding method in the
actual class.


Below answers are from MSDN.

When shall we prefer Abstract classes or Interface over other? 

  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.

  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.

  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.