RSS

Dynamic keyword in C# 4.0 !!

10 Oct

image9_207

You have to read or know more about DLR (Dynamic Language Run-time) from here (DLR)

The introduction of static type checking represented an  important milestone in the history of programming languages. In the 1970s, languages such as Pascal and C started enforcing static types and strong type checking. With static type checking, the compiler will produce an error for any call that fails to pass a method argument of the appropriate type. Likewise, you should expect a compiler error if you attempt to call a missing method on a type instance.

Other languages that push forward the opposite approach—dynamic type checking—have come along over the years. Dynamic type checking contradicts the idea that the type of a variable has to be statically determined at compile time and can never change while the variable is in scope. Note, however, that dynamic type checking doesn’t confer wholesale freedom to mix types, pretending they’re the same. For example, even with dynamic type checking, you still can’t add a Boolean value to an integer. The difference with dynamic type checking is that the check occurs when the program executes rather than when it compiles.

What is the dynamic type for ?

dynamic is a new static type that acts like a placeholder for a type not known until run-time. Once the dynamic object is declared, it is possible to call operations, get and set properties on it, even pass the dynamic instance pretty much as if it were any normal type.

Visual C# 2010 introduces a new type, dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to be concerned about whether the object gets its value from a COM API, from a dynamic language such as IronPython, from the HTML Document Object Model (DOM), from reflection, or from somewhere else in the program. However, if the code is not valid, errors are caught at run time.

For example, if instance method exampleMethod1 in the following code has only one parameter, the compiler recognizes that the first call to the method, ec.exampleMethod1(10, 4), is not valid because it contains two arguments. The call causes a compiler error. The second call to the method, dynamic_ec.exampleMethod1(10, 4), is not checked by the compiler because the type of dynamic_ec is dynamic. Therefore, no compiler error is reported. However, the error does not escape notice indefinitely. It is caught at run time and causes a run-time exception.

// ** The main method
static void Main(string[] args)
{
    ExampleClass ec = new ExampleClass();
    // The following call to exampleMethod1 causes a compiler error  
    // if exampleMethod1 has only one parameter. Uncomment the line 
    // to see the error. 
    //ec.exampleMethod1(10, 4);

    dynamic dynamic_ec = new ExampleClass();
    // The following line is not identified as an error by the 
    // compiler, but it causes a run-time exception.
    dynamic_ec.exampleMethod1(10, 4);

    // The following calls also do not cause compiler errors, whether  
    // appropriate methods exist or not.
    dynamic_ec.someMethod("some argument", 7, null);
    dynamic_ec.nonexistentMethod();
}

// ** The calss
class ExampleClass
{
    public ExampleClass() { }
    public ExampleClass(int v) { }

    public void exampleMethod1(int i) { }

    public void exampleMethod2(string str) { }
}

Using dynamic

It’s important to understand the concept that in the C# type system, dynamic is a type. It has a very special meaning, but it’s definitely a type and it’s important to treat it as such. You can indicate dynamic as the type of a variable you declare, the type of items in a collection or the return value of a method. You can also use dynamic as the type of a method parameter. Conversely, you can’t use dynamic with the typeof operator and you can’t use it as the base type of a class.

The following code shows how to declare a dynamic variable in the body of a method:

public void Execute()  
{ 
  dynamic calc = GetCalculator();
  int result = calc.Sum(1, 1);
}

If you know enough about the type of the object being returned by the GetCalculator method, you can declare the variable calc of that type, or you can declare the variable as var, letting the compiler figure out the exact details. But using var or an explicit static type would require you to be certain that a method Sum exists on the contract exposed by the type GetCalculator returns. If the method doesn’t exist, you get a compiler error.

With dynamic, you delay any decision about the correctness of the expression at execution time. The code compiles and is  resolved at run time as long as a method Sum is available on the type stored in the variable calc.

You can also use the keyword to define a property on a class. In doing so, you can decorate the member with any visibility modifier you like, such as public, protected, and even static.

dynamic vs. System.Object

Until the .NET Framework 4, having a method return different types according to different conditions was possible only by resorting to a common base class. You’ve probably solved this problem by resorting to System.Object. A function that returns System.Object makes available to the caller an instance that can be cast to nearly anything. So how is using dynamic better than using System.Object?

In C# 4, the actual type behind the variable that’s declared dynamic is resolved at run time, and the compiler simply assumes that the object in a variable declared dynamic just supports any operations. This means you can really write code that calls a method on the object you expect to be there at run-time.

var vs. dynamic

The keywords var and dynamic are only apparently similar. Var indicates that the type of the variable has to be set to the compile-time type of the initializer.

But dynamic means that the type of the variable is the dynamic type as available in C# 4.0. In the end, dynamic and var have quite opposite meanings. Var is about reinforcing and improving static typing. It aims to ensure that the type of a variable is inferred by the compiler looking at the exact type being returned by the initializer.

The keyword dynamic is about avoiding static typing altogether. When used in a variable declaration, dynamic instructs the compiler to stop working out the type of the variable at all. The type has to be intended as the type it happens to have at run time. With var, your code is as statically typed as it would have been had you opted for the classic approach of using explicit types in a variable declaration.

Another difference between the two keywords is that var can only appear within a local variable declaration. You can’t use var to define a property on a class, nor can you use it to specify the return value or a parameter of a function.

As a developer, you use the dynamic keyword with variables expected to contain objects of uncertain type such as objects returned from a COM or DOM API; obtained from a dynamic language (IronRuby, for example); from reflection; from objects built dynamically in C# 4.0 using the new expand capabilities.

The dynamic type doesn’t bypass type checks, though. It only moves them all to run time. If type incompatibilities are discovered at run time, then exceptions are thrown.

 
Leave a comment

Posted by on October 10, 2012 in Visual Basic .NET, Visual C# . NET

 

Tags: , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: