Saturday, November 7, 2009

In search for .Net 4.0 Features - dynamic.

If you are an edgy developer then you should be already knowing about the new version of .Net and about the keyword ‘dynamic’. C# 4.0 is adding support for the dynamic keyword, which introduces some aspects of dynamic languages to C#. I was reading on the some early bird posts pushed by some geeky folks upon the topic, and was sort of looking for a good opportunity to squeeze it into coding. After doing some research I found some scenarios which I thought it would work great with the dynamic type and also some areas it didn’t worked as expected.

Note:
Root is a public static property I used in sample which points to textbox in the main window.

1 - Hello World in dynamic.

This example demonstrates a ‘Hello World’ in dynamic.

class SimpleDynamic

{

public SimpleDynamic()

{

dynamic customer = new Customer();

customer.First = "Hello ";

customer.Last = "World";

customer.ID = 2009;

Root.Text = customer.HelloWorld();

}

}

public class Customer

{

public string First { get; set; }

public string Last { get; set; }

public int ID { get; set; }

public string HelloWorld()

{

return First + Last + ID.ToString();

}

}

2 - Convertions:

Dynamic eliminates the use of unboxing completely. We don’t require the value to be Casted if we do an assignment from a higher grade to lower grade.

class Convertions

{

public Convertions()

{

dynamic d1 = 7;

dynamic d2 = "a string";

dynamic d3 = System.DateTime.Today;

dynamic d4 = System.Diagnostics.Process.GetProcesses();

int i = d1;

string str = d2;

DateTime dt = d3;

System.Diagnostics.Process[] procs = d4;

Root.Text = "Check my code";

}

}

3 - COM Interop with Office.

The above feature creates the flexibility for dynamic to use it with COM interop.

// Without dynamic.

((Microsoft.Office.Interop.Excel.Range)excel.Cells[1, 1]).Value2 = "Name";

Excel.Range range = (Excel.Range)excel.Cells[1, 1];

// With dynamic.

excel.Cells[1, 1].Value = "Name";

Excel.Range range = excel.Cells[1, 1];

And here is another example.

public class CallMSO

{

//requires MSoffice to be installed.

public CallMSO()

{

var bankAccounts = new List<Account>

{

new Account { ID = 345678,Balance = 541.27 },new Account { ID = 1230221,Balance = -127.44}

};

CreateIconInWordDoc();

}

static void CreateIconInWordDoc()

{

var wordApp = new Word.Application();

wordApp.Visible = true;

wordApp.Documents.Add();

//check the arguments which contains dynamic

wordApp.Selection.PasteSpecial(Link: true, DisplayAsIcon: true);

}

}

public class Account

{

public int ID { get; set; }

public double Balance { get; set; }

}

4 - Using dynamic with Reflection:

This was the best part I liked while trying with this new syntax. Dynamic did a wonderful job here which helped me bypass some steps and of course result in some level of performance improvement.

dynamic mytype = Assembly.LoadFile(System.IO.Directory.GetCurrentDirectory() + @"\UnknownLib.dll").CreateInstance("UnKnownLib.UnkownClass");

MessageBox.Show(mytype.GetvaluePlus25(28).ToString());

If you think in old way you need to do something like to this.

Assembly myassm = Assembly.LoadFile(System.IO.Directory.GetCurrentDirectory() + @"\UnknownLib.dll");

Type mytype = myassm.GetType("UnKnownLib.UnkownClass");

System.Reflection.MethodInfo method = mytype.GetMethod("GetvaluePlus25", new Type[] { typeof(int) });

method.Invoke(myassm.CreateInstance("UnKnownLib.UnkownClass"),new object[] {20});

Unreferenced Remote Assembly.

namespace UnKnownLib

{

public class UnkownClass

{

public UnkownClass()

{

}

public int GetvaluePlus25(int val)

{

if (val + 25 <= int.MaxValue)

return val + 25;

else

return val;

}

}

}

5 - Using dynamic syntax to map an xml file:

XElement xel = XElement.Load(System.IO.Directory.GetCurrentDirectory() + @"\MyXml.xml");

dynamic del = new DynamicElement(xel);

dynamic textbox = textBox1;

textbox.Text = del.channel.title.ToString();

textbox.Text = textbox.Text + " - " + System.Environment.NewLine + del.channel.description;

foreach (var item in del.channel.items)

textbox.Text = textbox.Text + " - " + System.Environment.NewLine + item;

textbox.Focus();

Class Implmentation

public class DynamicElement : DynamicObject

{

private XElement actualElement;

public DynamicElement(XElement actualElement)

{

this.actualElement = actualElement;

}

public override bool TryGetMember(GetMemberBinder binder, out object result)

{

string name = binder.Name;

var elements = actualElement.Elements(name);

int numElements = elements.Count();

if (numElements == 0)

return base.TryGetMember(binder, out result);

if (numElements == 1)

{

if (elements.First().Attributes().Count() > 0 && elements.First().Attribute("IsCollection").Value == "True")

{

List<DynamicElement> list = new List<DynamicElement>();

for (int i = 0; i <>

{

list.Add(new DynamicElement(elements.First().Elements().ElementAt(i)));

}

result = list;

}

else

{

result = new DynamicElement(elements.First());

}

return true;

}

result = from e in elements select new DynamicElement(e);

return true;

}

public override string ToString()

{

return actualElement.Value;

}

}

6 - Call for static method – Do not work.

And here is some exception which comes with dynamic. This is something found not to be working with dynamic and it looks like Microsoft is planning to give support for this only on next version.

public class DynamicwithStaticObj

{

public DynamicwithStaticObj()

{

try

{

Root.Text = Addvalue(new Class1());

Root.Text += Addvalue(new Class2());

Root.Text += GetTransformString(new Class1().GetType());

Root.Text += GetTransformString(new Class2().GetType());

}

catch(Exception ex)

{

System.Windows.MessageBox.Show(ex.Message);

}

}

static string GetTransformString(dynamic mytype)

{

return mytype.AddValuefromstring("Hello World");

}

static string Addvalue(dynamic type)

{

return type.AddValue("Hello World");

}

}

Case N:

Well, you guys can also add the comments here and links to new cases where we can use dynamic. This would definitely help people who are new into C# 4.0.

Example:

Here is the sample which I worked available for download.

Dynamic_Sample

External Links/ References:

I found some folks who already did the paper work for me which I avoided the theory part. You can see the dynamic and .Net 4.0 Insides here in these links.

C# 4.0: Dynamic Programming - Explains the basics and layers of DLR –Dynamic Language Runtime.

Video Cast from MS DLR Development Team – Video explains the challenges and some technical insides for DLR.

MSDN References:

dynamic (C# Reference)

Dynamic Language Runtime Overview

Office Interop

Using Type dynamic

Dynamic Method Bags

Cross References:

http://weblogs.asp.net/bleroy/archive/2009/09/17/fun-with-c-4-0-s-dynamic.aspx

http://blogs.msdn.com/davidebb/archive/2009/10/23/using-c-dynamic-to-call-static-members.aspx

http://www.codeproject.com/KB/cs/dynamicfun.aspx

http://www.codeproject.com/KB/cs/CSharp4_Features.aspx

http://amazedsaint.blogspot.com/2009/09/fun-with-dynamic-objects-and-mef-in-c.html

Cross Blogs:

Programming Gallery Article: http://www.programminggallery.com/article_details.php?article_id=126

No comments:

Bookmark