Dynamic Object in CSharp Example

In the previous article you had go through about ExpandoObject. DynamicObject is powerful than the ExpandoObject. Let us look at the below example similar to the previous article.

dynamic docXml=new DynamicXml("PersonDetails.xml");
foreach (var person in docXml.Persons)
{
Console.WriteLine(person.FirstName);
}

public class DynamicXml:DynamicObject,IEnumerable
{
private dynamic _xml;
public DynamicXml(string fileName)
{
_xml = XDocument.Load(fileName);
}
public DynamicXml(dynamic xml)
{
_xml = xml;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var xml = _xml.Element(binder.Name);
if(xml!=null)
{
result = new DynamicXml(xml);
return true;
}
result = null;
return false;
}
public IEnumerator GetEnumerator()
{
foreach (var child in _xml.Elements())
{
yield return new DynamicXml(child);
}
}
public static implicit operator string (DynamicXml xml)
{
return xml._xml.Value;
}
}

Enjoy Programming…

Practical Use of Expando Object in CSharp

I am going to parse the below Person information in a XML file and Pull out the FirstName of each employee. There is a couple of way to do this .One way is by using Linq To XML like below

<?xml version="1.0" encoding="utf-8" ?>
<Persons>
<Person>
<FirstName>Jameel</FirstName>
</Person>
<Person>
<FirstName>Sreeraj</FirstName>
</Person>
<Person>
<FirstName>Vinayan</FirstName>
</Person>
<Person>
<FirstName>Anuraj</FirstName>
</Person>
<Person>
<FirstName>Niju</FirstName>
</Person>
</Persons>


private static void Main(string[] args)
{
var document = XDocument.Load("PersonDetails.xml");
var xElement = document.Element("Persons");
if (xElement != null)
foreach (var item in xElement.Elements("Person"))
{
var element = item.Element("FirstName");
if (element != null) Console.WriteLine(element.Value);
}
}

But it is little bit cluttered code. Let us try this same thing by using expando

var doc = XDocument.Load("PersonDetails.xml").AsExpando();
foreach (var person in doc.Persons)
{
Console.WriteLine(person.FirstName);
}

AsExpando is an extension method which create object graphs based on XDocument elements.You can reuse this method in this scenarios.

public static  class ExpandoXml
{
public static dynamic AsExpando(this XDocument xDocument)
{
return CreateExpando(xDocument.Root);
}


private static dynamic CreateExpando(XElement xElement)
{
var result = new System.Dynamic.ExpandoObject() as IDictionary<string, object>;
if(xElement.Elements().Any(x=>x.HasElements))
{
var list = new List<System.Dynamic.ExpandoObject>();
result.Add(xElement.Name.ToString(),list);
foreach (var childElement in xElement.Elements())
{
list.Add(CreateExpando(childElement));
}
}
else
{
foreach (var leafElement in xElement.Elements())
{
result.Add(leafElement.Name.ToString(),leafElement.Value);
}
}
return result;
}
}

Enjoy Programming..

Expando Object in CSharp

Expando Object

Once you create an instance of an Expando Object which is in the System.Dynamic namespace   then you have ability to arbitrarily add things to these object.

In the below code snippets I have create a new instance of ExpandoObject and add one property and method and then invoke that method.

dynamic expando = new System.Dynamic.ExpandoObject();
expando.Name = "Jameel";
expando.Display = new Action(() => Console.WriteLine(expando.Name));
expando.Display();

Output : Jameel

Enjoy Programming…

Dynamic Language Runtime Overview

Introduction

The DLR was created by Microsoft not only to support dynamic features in the main stream CLR languages but also to support new languages like Ruby and Python running on CLR running efficiently and effectively. DLR sit on the top of CLR and provide features these dynamic languages need like Call Site Caching. Call Site is the place you are performing some operations on a dynamic object. The DLR also supports other keywords such as Expando Object and Dynamic Object. This allows some interesting dynamic features n C#.

DLR

Enjoy Programming…

 

Dynamic Keyword Example of Excel Automation In CSharp – DEMO2

Let me show you another great use of dynamic keyword for COM interop. If you done any automation of Microsoft office application in the past then probably you familiar of adding COM assembly in to your project. I am going to do this without adding the assembly using dynamic.

class Program
{
static void Main(string[] args)
{
Type excelType = Type.GetTypeFromProgID("Excel.Application");
dynamic excel = Activator.CreateInstance(excelType);
excel.Visible = true;
excel.Workbooks.Add();
dynamic sheet = excel.ActiveSheet;
Process[] processes = Process.GetProcesses();
for (int i = 0; i < processes.Length; i++)
{
sheet.Cells[i + 1, "A"] = processes[i].ProcessName;
sheet.Cells[i + 1, "b"] = processes[i].Threads.Count;
}
}
}

It will open an excel file with all Process Name and Threads Count

Capture

 

dynamic keyword example in CSharp – Demo1

Inside Console Application we have an Employee class defined with FirstName property and a method called Display().

public class Employee
{
public string FirstName { get; set; }
public void Display()
{
Console.WriteLine("Hi, my name is {0}",FirstName);
}
}

Inside the Program imagine I am calling a method called GetName() which return an object

class Program
{
static void Main(string[] args)
{
}
public static object GetName()
{
return new Employee {FirstName = "Jameel"};
}
}

Then I am going to assign this method to an object in the main method

static void Main(string[] args)
{
object o = GetName();
}

How can I invoke the Display () method?
One way is call like below

Employee employee = GetName() as Employee;
employee.Display();

What we do when we don’t know the type of Display() method?
Ofcourse we can use reflection

object o = GetName();
o.GetType().GetMethod("Display").Invoke(o, null);

Dynamic typed variable could give the same result with less code.Note that C# and Visual Studio doesn’t give the intellisense.In compile time Compiler doesn’t know about the Display() method only runtime can understand it.

dynamic o = GetName();
o.Display();

Create one more class library by right clicking the solution and create a new class library project named Animals and add a new class named Animal with an method called Display()

public class Animal
{
public void Display()
{
Console.WriteLine("Elephant");
}
}

Our previous Console mode application don’t know about this because we not add the reference to this project. So that compiler doesn’t know about this assembly.
We can also the Display() method by dynamically loading this assembly.

Type animalType = Assembly.Load("Animals").GetType("Animal");
dynamic animal = Activator.CreateInstance(animalType);
animal.Display();

dynamic keyword help us to remove type casting from our code, reflection codes GetMember(),GetType() and GetProperty() and the Invoke method that try to set and get things. All of these things clean up with the dynamic keyword.

Enjoy Reading…

dynamic keyword in CSharp

Many of us like static type checking in C# because compiler can find early. But static type checking does for strict the way of write some code .You have to have type definition and metadata available at compile time in order to get work done. Before C# 4.0 it is impossible to interact with the dynamic languages such as Ruby and Python . There are also difficult in some scenarios like to work with COM objects. Anyone who trying to interop from C# code to legacy code In COM often pain . Perhaps you have felt some issues while interacting with Microsoft Office COM components to automate Word or Excel. In C# 4.0 Microsoft introduces a new keyword called dynamic. A dynamic variable is a statically typed variable is a dynamic variable. When C# compiler see the dynamically typed variable it turns off compile time check. Any operation to perform on a dynamic object reference by that variable like calling a method , setting up a property all will resolve at runtime.
dynamic person=new Person();
person.Name=”Jameel”;