Click here to Skip to main content
15,884,176 members
Articles / Programming Languages / C# 4.0
Article

Dynamic Keyword In C# 4.0 - Part 2

Rate me:
Please Sign up or sign in to vote.
4.56/5 (6 votes)
19 Apr 2011CPOL2 min read 19.2K   14   13
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:

C#
// 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.

C#
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. C#
    // 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. C#
    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. C#
    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:

C#
// 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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Software Industry
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
bartolo25-Apr-11 21:25
bartolo25-Apr-11 21:25 
GeneralRe: My vote of 5 Pin
Sanjay J Patolia25-Apr-11 21:31
Sanjay J Patolia25-Apr-11 21:31 
GeneralMy vote of 5 Pin
Gaston Verelst25-Apr-11 19:38
Gaston Verelst25-Apr-11 19:38 
GeneralRe: My vote of 5 Pin
Sanjay J Patolia25-Apr-11 21:31
Sanjay J Patolia25-Apr-11 21:31 
Generalneed to explain in deep- vote of 4 Pin
Pranay Rana21-Apr-11 19:09
professionalPranay Rana21-Apr-11 19:09 
hi it's good but if you can explain more in detail rather than giving link of msdn...

GeneralRe: need to explain in deep- vote of 4 Pin
Sanjay J Patolia25-Apr-11 21:33
Sanjay J Patolia25-Apr-11 21:33 
Generalpretty neat, but not much different from standard XLINQ which does the same Pin
Sacha Barber21-Apr-11 2:34
Sacha Barber21-Apr-11 2:34 
GeneralRe: pretty neat, but not much different from standard XLINQ which does the same Pin
bartolo25-Apr-11 21:27
bartolo25-Apr-11 21:27 
GeneralRe: pretty neat, but not much different from standard XLINQ which does the same Pin
Sacha Barber25-Apr-11 21:32
Sacha Barber25-Apr-11 21:32 
GeneralRe: pretty neat, but not much different from standard XLINQ which does the same Pin
bartolo25-Apr-11 21:41
bartolo25-Apr-11 21:41 
GeneralRe: pretty neat, but not much different from standard XLINQ which does the same Pin
Sacha Barber25-Apr-11 21:42
Sacha Barber25-Apr-11 21:42 
GeneralRe: pretty neat, but not much different from standard XLINQ which does the same Pin
Sanjay J Patolia25-Apr-11 21:35
Sanjay J Patolia25-Apr-11 21:35 
GeneralRe: pretty neat, but not much different from standard XLINQ which does the same Pin
Sacha Barber25-Apr-11 21:40
Sacha Barber25-Apr-11 21:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.