Skip Navigation Links

 CodeMatrixThe ultimate site for .NET programmers

Skip Navigation Links.    

Reflection in C#

The code below shows how to convert a string to different types using reflection.The generic method UpdateField takes a reference to a parameter to which a value needs to be assigned. The value is passed as an XmlNode. A child node of config is selected by name and the corresponding Parse method of the field parameter is invoked. This will work for int, bool, DateTime etc. The string type has to be handled separately as there is no Parse method. The compiler will not allow a direct conversion to T, so instead an upcast followed by a downcast is used.

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;

namespace Reflection
{
    public class XmlSupport
    {
        static public void UpdateField(ref T field, string xmlNodeName, XmlNode config)
        {
            try
            {
                XmlNode xmlNode = config.SelectSingleNode(xmlNodeName);

                if (field.GetType().Equals(typeof(string)))
                {
                    object obj = xmlNode.InnerText;
                    field = (T)obj;
                }
                else
                {
                    MethodInfo parseInfo = field.GetType().GetMethod("Parse", new Type[] { typeof(string) });
                    T convertedValue = (T)parseInfo.Invoke(null, new object[] { xmlNode.InnerText });
                    field = convertedValue;
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("Exception = " + ex.ToString());
            }
        }

        private bool ReadFromXml(string siteName)
        {
            XmlDocument xmlDoc = new XmlDocument();
            string path = "..\\..\\ReflectionTest.xml";
            string firmwareVersion = "";
            byte flags = 0;
            byte activeBattery = 0;
            uint solarPanelCurrent =0 ;
            sbyte temperature = 0;
            double voltageA = 0;
            double voltageB = 0;
            System.DateTime lastReportTime = DateTime.MinValue;

            try
            {
                xmlDoc.Load(path);
                XmlElement receiverNode = xmlDoc.DocumentElement;
                XmlSupport.UpdateField(ref firmwareVersion, "firmwareVersion", receiverNode);
                Console.WriteLine("firmwareVersion = " + firmwareVersion);
                XmlSupport.UpdateField(ref flags, "flags", receiverNode);
                Console.WriteLine("flags = " + flags.ToString());
                XmlSupport.UpdateField(ref activeBattery, "activeBattery", receiverNode);
                Console.WriteLine("activeBattery = " + activeBattery.ToString());
                XmlSupport.UpdateField(ref solarPanelCurrent, "solarPanelCurrent", receiverNode);
                Console.WriteLine("solarPanelCurrent = " + solarPanelCurrent.ToString());
                XmlSupport.UpdateField(ref temperature, "temperature", receiverNode);
                Console.WriteLine("temperature = " + temperature.ToString());
                XmlSupport.UpdateField(ref voltageA, "voltageA", receiverNode);
                Console.WriteLine("voltageA = " + voltageA.ToString());
                XmlSupport.UpdateField(ref voltageB, "voltageB", receiverNode);
                Console.WriteLine("voltageB = " + voltageB.ToString());
                XmlSupport.UpdateField(ref lastReportTime, "lastReportTime", receiverNode);
                Console.WriteLine("lastReportTime = " + lastReportTime.ToString());
                return true;
            }
            catch
            {
                return false;
            }
        }
        static void Main(string[] args)
        {
            XmlSupport xmlTest = new XmlSupport();
            xmlTest.ReadFromXml("CodeMatrix");
        }

    }
}
The output of the code example is as follows:
firmwareVersion = True
flags = 25
activeBattery = 10
solarPanelCurrent = 120
temperature = 10
voltageA = 125
voltageB = 210
lastReportTime = 6/25/2008 10:30:00 AM

Downloads
The source code in this article can be downloaded from below link. The code is complied with Microsoft Visual C# 2008.

Copyright © 2008 www.codematrix.net, All Rights Reserved. Disclaimer