Thursday, January 8, 2009

C# 3.0 Object Initialization Expressions and Anonymous Types

Part 1:

We know for standard object initializer, we have class Customer

public class Customer {
public int Age;
public string Name;
public string Country;
public Customer(string name, int age){
this.Name=name;
this.Age=age;
}
}
we know the above code has defult constructor Customer(){} and none default constructor: Customer(string name, int age){this.Name=name;this.Age=age;}

The standard syntax is:
Customer c1=new Customer();
Customer c2=new Customer("Jack",28);

If we want to set Country but not Age, we need to write the code following:

Customer customer=new Customer();
customer.Name="Mike";
customer.Country="France";

C# 3.0 introduces a shorter form of object initiallizaion syntax:
Customer customer=new Cusomer{Name="Mike",Coutry="France"};

For default constructor,we can aslo have the following syntax:
Customer c3=new Customer(){Name="Mike",Coutry="France"};
nondefault constructor:
Customer c4=new Customer("Paolo",21){Country="Italy"};
The c4 assignment above is equivalent to:
Customer c4=new Customer("Paolo",21);
c4.country="Italy";

******************
Part 2:
C# 3.0 Can have anonymous types:
var c5=new {Name="Mike",Coutry="France"};
This code generates a class under the scenes (you never see it), that looks like as below:
class __Anonymous1
{
public string Name;
public string Country;
}

__Anonymous1 c5=new __Anonymous1()
c5.Name="Mike";
c5.Country="France";

Tuesday, January 6, 2009

Delegate, Ananymous Method and Lamda Expression

I am going to copy this one from msdn, as it has good explanation on Ananymous method and lamda expressions:

The contents below are copied from msdn:

"

In C# 1.0, you created an instance of a delegate by explicitly initializing it with a method that was defined elsewhere in the code. C# 2.0 introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation. C# 3.0 introduces lambda expressions, which are similar in concept to anonymous methods but more expressive and concise. These two features are known collectively as anonymous functions. In general, applications that target version 3.5 and later of the .NET Framework should use lambda expressions.

The following example demonstrates the evolution of delegate creation from C# 1.0 to C# 3.0:

C# Copy Code
class Test
{
delegate void TestDelegate(string s);
static void M(string s)
{
Console.WriteLine(s);
}

static void Main(string[] args)
{
// Original delegate syntax required
// initialization with a named method.
TestDelegate testdelA = new TestDelegate(M);

// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
TestDelegate testDelC = (x) => { Console.WriteLine(x); };

// Invoke the delegates.
testdelA("Hello. My name is M and I write lines.");
testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");

// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
Hello. My name is M and I write lines.
That's nothing. I'm anonymous and
I'm a famous author.
Press any key to exit.
*/

"

Notice ananymous type and lamda expressions all return to delegate type:

ex1:

A. Traditional delegate:

class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = new SomeDelegate(SomeMethod);
del();
}

void SomeMethod()
{
Console.WriteLine("Hello");
}
}

For the traditional delegate, we should new a delegate and pass the function name as signature to the delegate to call back.

B.Ananymous Method

class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = delegate()
{
Console.WriteLine("Hello");
};
del();
}
}

C. Lamda Expression

class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = () => Console.WriteLine("Hello") ;
del();
}
}

For Lamda Expression, it has syntax

parameters => expression

And:

(int x) => { return x + 1; } is the same as (int x) => x + 1 ; is the same as x=>x+1;

For the Array or class which impliments IEnumerable interface, it has Where extension method, public static IEnumerable Where(this IEnumerable source, Func predicate); predicate is one kind of delegate, we can also place the lamda expression in Where() method:

ex2:
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };



foreach (int i in source.Where(x => x > 5))

Console.WriteLine(i);


ex3
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
foreach (int i in source.Where(

x =>
{

if (x <= 3)

return true;//notice here return true or false

else if (x >= 7)

return true;

return false;

}

))

Console.WriteLine(i);

The lamda expression in Where() method return true or false, because for the predicate delegate, there is definition:

public delegate bool Predicate(
T obj
)
true if obj meets the criteria defined within the method represented by this delegate; otherwise, false.