Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Dynamic Keyword In C# 4.0 - Part 2

0.00/5 (No votes)
19 Apr 2011 1  
Superb Example To Traverse an XML File. One should have an understanding of Dynamic Keyword before reading this article which I explained in Part 1

Introduction

Please refer to the below links before reading this article. It gives an idea of how to use TryGetMember method of DynamicObject class which is necessary to understand this article because we used it in our example for XmlNavigation.

Now, manipulating XElements can be done with methods of XElement objects and the syntax may be:

// Creates an XElement dynamically
XElement xmlNavigation = XElement.Parse(@"
                            <Emails>
                                <Email>
                                    <Id>1</Id>
                                    <Description>sanjay.patolia@gmail.com</Description>
                                </Email>
                                <Email>
                                    <Id>2</Id>
                                    <Description>sanjay.patolia@patni.com</Description>
                                </Email>
                            </Emails>
                            ");

var email = xmlNavigation.Elements("Email"); 

In the above example, to fetch all the "Email" elements, we used Elements("Emails") statement. In the same way, we use other methods too to manipulate other XML reading oprations. Here, though our work has been done for fetching elements, it does not come into easily readable format. We can achieve that kind of functionality using DynamicObject class and a dynamic keyword, which allows us to navigate through XML in easily readable format. We just need to keep track of XmlStructure.

Let's talk a bit about DynamicObject class.

DynamicObject class allows us to implement operations dynamically, when we try to get member values or set member values. Please refer to the above link for more information on DynamicObject.TryGetMember method. Here, we will look at TryGetMember method of DynamicObject class, which will be called when we will try to get values of properties which are not implemented in the class.

Let us see an example of XML Navigation using DynamincObject class and a dynamic keyword.

namespace XmlNavigationUsingDynamic
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creates an XML file in memory
            dynamic xmlNavigation = new XmlNavigationUsingDynamic
                (XElement.Parse(@"
                            <Emails>
                                <Email>
                                    <Id>1</Id>
                                    <Description>sanjay.patolia@gmail.com</Description>
                                </Email>
                                <Email>
                                   <Id>2</Id>
                                   <Description>sanjay.patolia@patni.com</Description>
                                </Email>
                            </Emails>
                            "));
 
            // Taking collection of "Description" elements into IEnumerable<XElement>
            // Here, we can also take it into var type instead of IEnumerable<XElement>
            IEnumerable<XElement> descriptionNodes = xmlNavigation.Email.Description;
 
            // Printing an elements "Description"
            descriptionNodes.ToList().ForEach(emailDesc =>
            {
                Console.WriteLine(emailDesc);
            });
 
            Console.ReadKey(true);
        }
    }
 
    /// <summary>
    /// XmlNavigationUsingDynamic class
    /// This allows us to perform dynamic operations
    /// </summary>
    public class XmlNavigationUsingDynamic : DynamicObject, IEnumerable<XElement>
    { 
        /// <summary>
        /// Xml node to be crated
        /// </summary>
        IEnumerable<XElement> node = null;
 
        /// <summary>
        /// Initializes node member
        /// </summary>
        /// <param name="nodes">XElements parameters</param>
        public XmlNavigationUsingDynamic(params XElement[] nodes)
        {
            node = nodes;
        }
 
        /// <summary>
        /// Allows to implement code for dynamic operations
        /// will be called when we try to Get any member of this class
        /// </summary>
        /// <param name="binder">Here we are using this to fetch 
        /// name of the member which is being called</param>
        /// <param name="result">Allows to assign a value to a property 
        /// which is being called
        /// For example: 
        /// When we say, 
        ///         xmlNavigation.Email, it will call this method with 
        ///         name in binder object and 
        ///         when we set result object that will be returned to the caller
        /// </param>
        /// <returns>true or false to say whether it was successful or not</returns>
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            var genericNode = node.Elements(binder.Name).ToArray();
            result = new XmlNavigationUsingDynamic(genericNode);
            return true;
        }
 
        /// <summary>
        /// Gets enumerator
        /// </summary>
        /// <returns></returns>
        public IEnumerator<XElement> GetEnumerator()
        {
            return node.GetEnumerator();
        }
 
        /// <summary>
        /// Calls GetEnumerator method
        /// </summary>
        /// <returns>IEnumerator</returns>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

In the above example:

  1. // Creates an Xml file in memory
    dynamic xmlNavigation = new XmlNavigationUsingDynamic
    	(XElement.Parse(@"
                            <Emails>
                                <Email>
                                    <Id>1</Id>
                                    <Description>sanjay.patolia@gmail.com</Description>
                                </Email>
                                <Email>
                                    <Id>2</Id>
                                    <Description>sanjay.patolia@patni.com</Description>
                                </Email>
                            </Emails>
                            "));

    creates an XML file in memory.

  2. xmlNavigation.Email

    xmlNavigation is an object of XmlNavigationUsingDynamic class and .Email is a member (considering a member) of that class. So it is trying to access that member of that class. This statement will call the TryGetMember method, it performs an operation and sets result object which will be the base of "Description", because the result object is set to an object of XmlNavigationUsingDynamic class.

  3. xmlNavigation.Email.Description

    Description will be called from result (object set from TryGetMember method) and returns IEnumerable<XElement> because we have implemented IEnumerable<XElement> and node.GetEnumerator() method is called which is implemented from IEnumerable interface and returns IEnumerable<XElement> so at last we are iterating it to get element "Description".

So, look at the difference in traversing the XML file:

// Using typical XML traversing using XElements.
var email = xmlNavigation.Elements("Email");
 
// Using DynamicObject class XML traversing.
// We can use var here as required.
IEnumerable<XElement> descriptionNodes = xmlNavigation.Email.Description;

Thus, in this way we can perform other XML navigation operations too.

History

  • 19th April, 2011: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here