Dynamic key word in c#
Hi in this post i want to write about Dynamic keyword and how we can use that.
Let me explain you my problem
Actually from the past few months i am working on a project called “.Net conversion”. That is We are having some of our code in vb component. As Microsoft withdrew its support for vb we decided to make a move to .Net
When converting the code we had number of challenges. But we succeeded in that process. There are few features in vb code that were not supported by .Net(I mean we don’t have them directly but we can achieve them using some techniques).
So let me discuss few of them here.
Use of variant key word in Visual Basic 6.0
Let us take a simple example of VB code that makes use of Variant keyword
Private Sub Command_Click() Dim arrNames As Variant arrNames = ReturnNames(textBox.Text) End Sub Private Function ReturnNames(ByVal name As String) Dim arrayOfNames As Variant Dim arrStates() As String Dim states As String states = "Alaska,Indiana,NY,MA" arrStates = Split(states, ",") If name = "US" Then arrayOfNames = arrStates 'Here we are assigning array to variant Else arrayOfNames = name 'Here we are assigning string to variant End If ReturnNames = arrayOfNames End Function
Let me explain you what i am trying to do here.
Actually there are 2 function in the above vb code
1.Command_Click()
2.ReturnNames
There is a vb form that contains a text box and a button. Command_Click() is called on button click in the vb form. It reads the value entered in the textbox of vb form.
ReturnNames function it accepts a string and returns a variant. So what i am actually trying to do here is.
1. I am having a string of states present in US(states variable)
2.I am trying to split the states and assigning that to arrStates. arrStates is an array that contains list of States.
3. I am trying to read the value entered in the vb form text box. If the value is “US” then i am trying to return all the states present inside US(array of states).
4. If the value entered in the textbox is something other than US then i am trying to return the name entered(This is simply a string)
So ReturnNames function returns either an array or string.
Note : This is just a simple example and this example doesnt make any sense in realtime and my opinion is to just show how to use variant key word.
So in VB a single function can return any type like array or string or int etc. This can be achieved by declaring a variable as variant
1.So with variant key word in vb there is no necessity to define its type at runtime.
2.It can be assigned any value.
Now let us see some similar concepts in C#
There are few concepts in c# that can bring dynamic behavior to the code. they are
1.Var
2.object
3.dynamic
var keyword in C#
Var is an implicit type. It is an alias for all the types in c#. That is we dont need to declare a variable explicitly with the type and we can simply use var keyword.
var a = 10;
a = a + 10;
a=a+"10";//This line throws a compile time error.
Console.WriteLine(a.GetType());
When we assign a value for var at declaration time then that particular variable should be assigned only that variable.
So the type of the variable is assigned at compile time itself.
So va key word in c# is not at all same a variant in VB code
object keyword in C#
object class is the base class for all the classes in the framework. So when we declare an variable as object then that can be casted to anything.
object a = 10;
a = a + 10;//This throws an error at compile time
a=a+"10";//This line throws a compile time error.
a=Convert.Tostring(a)+"10"; //Value of a is 1010
a=Convert.ToInt(a)+"10";//Value of a is 1010
a=Convert.ToInt(a)+10; //value of a is 20
a = Convert.ToString(a )+ 10;//value of a is 1010
Console.WriteLine(a.GetType());//Returns string
So from above code we can understand few things.
1. The type of the variable declared as object differs based on the statement and context it is used.
2. So When ever we are performing some operation on variable declared as object we are supposed to explicitly perform casting.
3.We can assign values of different types to variable created using object.
4.It checks the types at complie time
dynamic keyword in C#
dynamic keyword was introduced in C# 4. A variable declared with dynamic can be assigned any value.
dynamic a = 10;
a = a + 10;
a = a + "10"; //Value of a is 1010
a = Convert.ToString(a) + 10;//value of a is 1010
Console.WriteLine(a.GetType());//Returns string
In the following line, no cast is required, because the type is identified at run time only:
a= a+ 10;
You can assign values of different types to dynamicExample:
a= “test”;
Some points
1. The type of the variable declared as dynamic differs based on the statement and context it is used.
2. So When ever we are performing some operation on variable declared as dynamic , no need to perform any casting. As type is checked at runtime
3.We can assign values of different types to variable created using dynamic.
4.It checks the types at runtime.
A Difference between Object and dynamic keyword
When ever we are using dynamic key word we can assign any thing to it and it will be resolved at runtime but that is not the case with object keyword.
Let us take a small example that caught my attention.
object stringArray = new string[10];
stringArray[0] = "Pavan"; //Throws compile time error
stringArray[1] = "Rajesh"; //Throws compile time error
stringArray[2] = "Harsha"; //Throws compile time error
object[] stringarray1 = new String[10];
stringarray1[0] = "Pavan";
stringarray1[1] = "Rajesh";
stringarray1[2] = "Harsha";
dynamic stringArrayUsingDynamic = new string[10];
stringArrayUsingDynamic[0] = "Pavan";
stringArrayUsingDynamic[1] = "Rajesh";
stringArrayUsingDynamic[2] = "Harsha";
In the above code when we apply indexing on stringArray it is throwing a compile time error. So even though we were able to assign an object of string array to stringArray at the time of adding values it is throwing a compile time error.
So we are supposed to create an object[] for this purpose.
Dynamic as return type of a function
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DynamicKeyword
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter US for array. OR enter somevalue to get string as returntype from ReturnVariable function");
string input_from_user = Console.ReadLine();
dynamic z = ReturnVariable(input_from_user);
}
static dynamic ReturnVariable(string input_from_user)
{
dynamic k = "";
string states = "Alska,Indiana,MA,NY";
k = states.Split(',');
if (input_from_user.Contains("US"))
{
k = k;
}
else
{
k = "pavan";
}
return k;
}
}
}
Another beautiful feature of Dynamic—It simplifies code involved in refection
Suppose let us assume that there is a dll in the gac or from some path and we want to load it at runtime and call the methods present in it.
Let us see how we do that in traditional way.
string path="C:\\Test.dll";
Assembly assm= Assembly.LoadFile(path);
Type typ = assm.GetTypes()[0];
object d= Activator.CreateInstance(typ);
object[] parameters = new object[]{ "param1,param2" };
object returnValue = typ.InvokeMember("Test", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, null, d, parameters);
So inorder to call the “Test” method present inside Test.dll we need to follow these steps.
1.Load the assembly using Assembly.Load
2.Get the type using Assembly.GetType()
3.Now create the object using Activator.CreateInstance()
4.Call InvokeMember with all the required parameters
The above code can be simplified to some extent using Dynamic keyword
string path="C:\\Test.dll";
Assembly assm= Assembly.LoadFile(path);
Type typ = assm.GetTypes()[0];
dynamic d= Activator.CreateInstance(typ);
d.Test("param1","Param2");
Absolutely written subject material, Really enjoyed reading through.
Vernell
September 25, 2012 at 9:31 am
Difference between Var,Dynamic and object explained nicely ……
Dhiren Kumar Kaunar
September 26, 2012 at 7:27 am
Thank you So much Dhiren…:)
pavanarya
September 26, 2012 at 9:20 am
Nice…..
JP
October 4, 2012 at 5:13 pm
nice work
monjurulhabib
October 14, 2012 at 12:12 am