Sunday, May 23, 2010

Here I’ll talk about some new features of C# 4.0

At the beginning remember that; 

In every new release of c# there is a major new feature than the oldest one

Remember in C# 2.0 (Generics), C# 3.0 (Linq), and here (dynamic programming support)

1. Named and optional parameters: Now declare optional parameters simply by providing a default value for it. And call params by name: like so,

        // Definition of the method
public void Method(int x, int y = 1, int z = 2)


// Using the optional params
Method(1); // same as Method(1, 1, 2);
Method(1, 2); // same as Method(1, 2, 2);
Method(1, 2, 3);

// Named params called, note arbitrary order and missing y
Method(z: 1, x: 2);

2. dynamic object:

A new type has been introduced called dynamic. The idea is that you can call any operation on the dynamic type you want, the compiler won’t check it at compile-time, but figure it out at runtime. A dynamic object is assumed to support any operation at compile-time, only at runtime will you get an error. The result of any dynamic operation is of type dynamic.

        // Instantiation
dynamic d = 7; // implicit conversion
dynamic d = GetStudentData(); //GetStudentData() returns object of type Student class

// Operations on dynamic types

d.f = d.P; // getting and settings fields and properties
d["one"] = d["two"]; // getting and setting thorugh indexers
int i = d + 3; // calling operators

// in the previous examples if f,p are not properties on the Student class and also there is no indxer it will be compiled successfully ,it will be detected at runtime.

C# fast-food by:

Eng.Waleed abou-zaid

Senior Software Developer

Harf Information Technology

MCSD.Net,MCAD.Net,MCP,A+,N+ certified