Tag Archives: C# 4.0

C# 4.0 new features

In every new release of C# there is a major new feature like in C# 2.0 (Generics), C# 3.0 (Linq), and here C# 4.0 (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       

        d.f = d.P;           // getting and settings types 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.

Leave a comment

Filed under C#