Sponsored Ad

Thursday, October 22, 2009

Dynamic C#

Visual C # 2010 introduced a new dynamic. The guy is a static type, but an object of dynamic type ignores the static type checking. In most cases, works like text object. At compile time, an element is written as a dynamic that is supposed to support any operation. Therefore, you do not have to worry about whether the object has its value from a COM API, in a dynamic language like IronPython, from the HTML Document Object Model (DOM), reflection, or from somewhere else in the program. However, if the code is not valid, the errors are caught at runtime.

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 four 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's caught at run time and causes a run-time exception.

static void Main(string[] args)
{
    ExampleClass ec = new ExampleClass();
    // The following line causes a compiler error if exampleMethod1 has only
    // one parameter.
    //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();
}

 

C#

class ExampleClass
{
    public ExampleClass() { }
    public ExampleClass(int v) { }

    public void exampleMethod1(int i) { }

    public void exampleMethod2(string str) { }
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers