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…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s