Click here to Skip to main content
15,880,956 members
Articles / Desktop Programming / Win32

A Basic Tour To Dynamic Keyword - Dotnet 4.0

Rate me:
Please Sign up or sign in to vote.
3.30/5 (16 votes)
27 Oct 2010CPOL4 min read 31.1K   94   11   11
This short tutorial will give the idea about the usage of Dynamic Keyword in dotnet 4.0

Introduction

With the advent of C#4.0, we have a new friend… Dynamic.

It references objects which happens to or not to exist at runtime. Put in different term, it allows late binding.

Using the code

Let us start with a very basic example

Example 1: Simple Addition

dynamic dynVar = 10</span />;
dynVar += 10</span />;
Console.WriteLine(dynVar);

Output is: 20

Example 2: Simple Concatenation

dynVar += "</span /> Hello"</span />;
Console.WriteLine(dynVar);

Output is: 10 Hello

But consider this

var varVariable = 10</span />;
varVariable += "</span /> Hello"</span />;

This will yield a compile time error

Cannot implicitly convert type 'string' to 'int'

However the below works

object obj = 10</span />;
obj += "</span />Hello"</span />;
Console.WriteLine(obj);

Reason: It is a specific type inferred from context and does not change type like dynamic does

Example 3:

Consider the below

dynamic dynClass = new</span /> MyClass()
{
  IntProperty = 1</span />
                    
  , StringProperty = "</span />A string property"</span />
                    ,
  , StringField = "</span />A string filed"</span />
                    ,
  , DecimalField = 10d
};

And

var varClass = new</span /> MyClass()
{
   IntProperty = 1</span />
                    ,
   StringProperty = "</span />A string property"</span />
                    ,
   StringField = "</span />A string filed"</span />
                    ,
   DecimalField = 10d
};

TestCase1 : Display Valid Property value

Console.WriteLine(dynClass.IntProperty); //</span />Using dynamic object
</span />Console.WriteLine(varClass.IntProperty); //</span />using var object
</span />

Worked with a charm with the output being 1 for each case.

TestCase2 : Display InValid Property value

Console.WriteLine(dynClass.InvalidProperty); //</span />Using dynamic object</span />

Compiled fine

Runtime Error: 'DynamicExample.MyClass' does not contain a definition for 'InvalidProperty'

 Console.WriteLine(varClass.InvalidProperty); //</span />using var object
</span /> 

Complie time error DynamicExample.MyClass' does not contain a definition for 'InvalidProperty' and no extension method 'InvalidProperty' accepting a first argument of type 'DynamicExample.MyClass' could be found (are you missing a using directive or an assembly reference?)

TestCase3 : Display Valid Function Call

Console.WriteLine(dynClass.ValidMethod()); //</span />Using dynamic object
</span />Console.WriteLine(varClass.ValidMethod()); //</span />using var object
</span />

As expected, worked fine with the output being Hello

TestCase4 : Display InValid Function Call

Console.WriteLine(dynClass.InvalidMethod()); //</span />Using dynamic object
</span />

Runtime error 'DynamicExample.MyClass' does not contain a definition for 'InvalidMethod'

Console.WriteLine(varClass.InvalidMethod()); //</span />using var object
</span />

Compile time error as expected 'DynamicExample.MyClass' does not contain a definition for 'InvalidMethod' and no extension method 'InvalidMethod' accepting a first argument of type 'DynamicExample.MyClass' could be found (are you missing a using directive or an assembly reference?)

Example 4: Runtime invocation

Consider the below two cases

Case 1

//</span />Case 1: Using reflection to invoke member
</span />var</span /> type = typeof</span />(DynamicExample.MyClass);
var</span /> res1 = type.InvokeMember(
            "</span />Add"</span />
            , BindingFlags.InvokeMethod
            , null</span />
            , Activator.CreateInstance(type)
            , new</span /> object</span />[] { 10</span />, 20</span /> });
Console.WriteLine("</span />Addition of two number using reflection= "</span /> + res1);

Case 2

//</span />Case 2: Using Dynamic to invoke member 
</span /> dynamic res2 = ((dynamic)Activator.CreateInstance(typeof</span />(DynamicExample.MyClass))).Add(10</span />, 20</span />);
 Console.WriteLine("</span />Addition of two number using dynamic= "</span /> + res2);

The output being same in both the cases.

Example 5: Calling Iron Python Function From C# 4.0

Here I will give a short demo as how to call a method written in IronPython 2.6 and making a dynamic invocation to the method from C# environment.

Step 1: Download the latest version of Iron Python from Code Plex

Step 2: Install the software.

Step 3: For this demo I am using “first.py” python file located inside the Tutorial Folder

1.jpg

The file has two methods

a) Add

b) Factorial.

For this demo purpose, let us only invoke the Add method that performs addition of two numbers being supplied as parameters to the method.

Step 4: I am using a console application for the demo purpose. The very first thing we need to do is to add the dlls as shown under

2.jpg

Step 5: The function invocation happens in just three steps as shown below

static void Main(string[] args)
        {
            //Step 1: 
            //Creating a new script runtime             
            var ironPythonRuntime = Python.CreateRuntime();

            try
            {
                //Step 2:
                //Load the Iron Python file/script into the memory
                //Should be resolve at runtime
                dynamic loadIPython = ironPythonRuntime.UseFile("first.py");

                //Step 3:
                //Invoke the method and print the result
                Console.WriteLine(
                string.Format("Addition result from IronPython method for {0} 
                 and {1} is {2}",100,200, loadIPython.add(100, 200)));
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey(true);
            
        }

The very first line

var ironPythonRuntime = Python.CreateRuntime();

loads the Iron Python libraries along with the DLR code needed to execute the python script.

Second line

dynamic loadIPython = ironPythonRuntime.UseFile("</span />first.py"</span />);

loads the python script into memory. The significance of the dynamic variable(loadIPython) here is being the fact that Python calls are resolve at runtime.

The last line i.e.

Console.WriteLine(string.Format("</span />
     Addition result from IronPython method for {0} and {1}
     is {2}"</span />, 100</span />,200</span />,
     loadIPython.add(100</span />, 200</span />)) );

Is simply to invoke the Python method and to display the result.

Step 6: And here is the output

4.jpg

Example 6: Calling Iron Ruby Function From C# 4.0

Here I will give a short demo as how to call a method written in IronRuby 1.1 and making a dynamic invocation to the method from C# environment.

Step 1: Download the latest version of Iron Ruby from Code Plex

Step 2: Install the software.

Step 3: For this demo I am using add.rb Ruby file which has only one Add method that performs addition of two numbers being supplied as parameters to the method.

Step 4: I am using a console application for the demo purpose. The very first thing we need to do is to add the dlls as show below

5.jpg

Step 5: The function invocation happens in just three steps as shown below

static void Main(string[] args)
        {
            //Step 1: 
            //Creating a new script runtime   
            var ironRubyRuntime = Ruby.CreateRuntime();

            try
            {
                //Step 2:
                //Load the Ruby file/script into the memory
                //Should be resolve at runtime
                dynamic loadIRuby = ironRubyRuntime.UseFile(@"add.rb");

                //Step 3:
                //Invoke the method and print the result
                Console.WriteLine(
                string.Format("Addition result from Iron Ruby method for {0} and 
                {1} is {2}",100, 200, loadIRuby.add(100, 200))
                                 );               
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey(true);
        }

The very first line

var ironRubyRuntime = Ruby.CreateRuntime();

loads the Iron Ruby libraries along with the DLR code needed to execute the python script.

Second line

dynamic loadIRuby = ironRubyRuntime.UseFile(@"</span />add.rb"</span />);

loads the Ruby script into memory. The significance of the dynamic variable(loadIRuby) here is being the fact that Ruby calls are resolve at runtime.

The last line i.e.

Console.WriteLine(string.Format
("</span />Addition result from Iron Ruby method for {0} 
and {1} is {2}"</span />, 100</span />, 200</span />, 
loadIRuby.add(100</span />, 200</span />)));

Is simply to invoke the Ruby method and to display the result.

Step 6: And here is the output

7.jpg

References

http://msdn.microsoft.com/en-us/library/dd264736.aspx

Conclusion:

In this short tutorial we have seen how the dynamic keyword helps us in various situations. Having said that, there are some pitfalls of this keyword like runtime checking and henceforth breaks the hallmark of C#’s strong type checking. Hope this tutorial has shed some idea on how, where to use dynamic and also how to invoke IronPython and IronRuby methods from C# 4.0.

Comments on the topic are highly appreciated for the improvement of the topic.

Thanks for reading the article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralMy vote of 1 Pin
Batzen28-Oct-10 1:57
Batzen28-Oct-10 1:57 
GeneralMy vote of 1 Pin
SledgeHammer0127-Oct-10 7:26
SledgeHammer0127-Oct-10 7:26 
GeneralMy vote of 1 Pin
Steve Maier27-Oct-10 4:49
professionalSteve Maier27-Oct-10 4:49 
GeneralMy vote of 1 Pin
krishnaraj4027-Oct-10 1:07
krishnaraj4027-Oct-10 1:07 
GeneralMy vote of 1 Pin
M8ix26-Oct-10 18:41
M8ix26-Oct-10 18:41 
GeneralMy vote of 1 Pin
Keith Barrow26-Oct-10 7:03
professionalKeith Barrow26-Oct-10 7:03 
GeneralMy vote of 1 Pin
Nagy Vilmos26-Oct-10 5:46
professionalNagy Vilmos26-Oct-10 5:46 
GeneralFormatting Pin
Richard MacCutchan26-Oct-10 3:28
mveRichard MacCutchan26-Oct-10 3:28 
GeneralRe: Formatting Pin
Niladri_Biswas27-Oct-10 0:10
Niladri_Biswas27-Oct-10 0:10 
GeneralMy vote of 5 Pin
Arina Biswas24-Oct-10 23:14
Arina Biswas24-Oct-10 23:14 
GeneralMy vote of 4 Pin
Eshwer24-Oct-10 22:49
Eshwer24-Oct-10 22:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.