Sunday, July 27, 2008
This is part 2 of C# 3.0: From "C++" to "Ruby" Family - Part I. In this part, I will brief the remaining part of "Generics".
Applying your constraints on Generic
What is the real usage of allowing any type into my generic method or in class. We know that TransferAccount() method relies on bank account which could be either savings, current, etc. It is not sensible to allow any type of objects as parameter. In such case, you can apply constraint on Generic by C#2.0 new keyword "where" as:
- generic type should be derived from this base class or should implement this interface (where T : base-class-name interface-name)
- generic type should be a none other than class for example struct (where T:class)
- generic type should have default constructor (where T : new())
For example, let us refactor our previous code like:
public TAccount CreateInstance<TAccount>(long accountNumber) where T : Account{
// create either savings, current account instance based on account number
}
The above code apply the constraint "only allow types derived from "Account" base class" into CreateInstance.
Anonymous Methods followed by Lamda Expression:
I had been unbalanced with OOP/procedural and functional programming concepts year back, because of the mix of these two concepts will make programming more tasteful and better. Because of this reason only, I love Ruby and JavaScript programming (of course C# is mixed in the life of a programmer).
One nice thing about functional programming is "closure" methods or "lamda expression".
Let us see our famous C# delegate:
delegate int Calculator(int a, int b);
static void Main(string[] args)
{
Calculator add = Add;
Console.WriteLine(add(2, 3));
Console.ReadLine();
}
public static int Add(int x, int y)
{
return x + y;
}
In the above code, I have declared a delegate "Calculator" and used this for "Add" method. As per "Not every theoretical can be used in practical", in most of the situation, we are in a position to define a delegate and then we need to apply one or more methods one time only like the above example. In such case, defining a delegate and then defining method for that delegate results less "beautiful code". C# 2.0 introduced "anonymous methods" eliminates and save developer productivity and the code. By this,
Calculator add = delegate(int x, int y) { return x + y; };Without defining "Add" method, we can define anonymous methods.
Console.WriteLine(add(2, 3));
Why Lamda Expression?
This is in place of anonymous delegate instance . See the below code:
Calculator add = (int x, int y) => { return x + y; };Visually whats the different? "delegate" has been removed and "=>" introduced. Otherwise, the same in visual perspective. But under C#'s regime, lamda expression is something different from "anonymous methods". (For me, it provides functional programming feature.)
Console.WriteLine(add(2, 3));
The code within {...} denotes an expression tree of type Expression<T>
0 comments:
Post a Comment