posts - 234, comments - 480, trackbacks - 56

My Links

News




I am born in Bangladesh and currently live in Melbourne, Australia. I am a co-founder and core developer of Pageflakes www.pageflakes.com and CEO at Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh.

I also created SmartCodeGenerator

Some of my articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET
Smart Code Generator .NET: Usage Overview
Smart Code Generator .NET: Architectural Overview
Smart Code Generator .NET: using with NAnt and Cassini

Archives

Free Programming Language Training

Reflection Tips on Nested Classes: Use (+) plus instead of (.) dot with Assembly.GetType

Lets say we want to use reflection to generate a mock test case for this following Nested Class ClientAddress.class

When we load an assembly from a disk dynamically, we can use GetType to look up a type defined in the assembly.

Example:

Assembly assembly = Assembly.GetAssembly(typeof(TheClient));
Type type = assembly.GetType("ConsoleApplicationUsePlus.TheClient");
object obj = Activator.CreateInstance(type);

But one point to remember here, to get Assembly.GeType working with nested classes a Plus(+) sign should precede the nested class. To get a parent class and a nested class we have to use

Type.GetType("ParentClass+NestedClass") //Notice the Plus(+) sign.

So in the above example to get ClientAddress we would have to write something like this.

Assembly assembly = Assembly.GetAssembly(typeof(TheClient));
Type type = assembly.GetType("ConsoleApplicationUsePlus.TheClient+ClientAddress"); //Notice the Plus(+) sign.
object obj = Activator.CreateInstance(type);


This is well documented in MSDN and here is the full chart
http://msdn.microsoft.com/en-us/library/aa332510.aspx

To Get An unmanaged pointer to MyType
Use Type.GetType("MyType*")

To Get An unmanaged pointer to a pointer to MyType
Use Type.GetType("MyType**")

To Get A managed pointer or reference to MyType
Use Type.GetType("MyType&"). Note that unlike pointers, references are limited to one level.

To Get A parent class and a nested class
Use Type.GetType("MyParentClass+MyNestedClass")

To Get A one-dimensional array with a lower bound of 0
Use Type.GetType("MyArray[]")

To Get A one-dimensional array with an unknown lower bound
Use Type.GetType("MyArray[*]")

To Get An n-dimensional array
Use A comma (,) inside the brackets a total of n-1 times. For example,System.Object[,,] represents a three-dimensional Object array.

To Get A two-dimensional array's array
Use Type.GetType("MyArray[][]")

To Get A rectangular two-dimensional array with unknown lower bounds
Use Type.GetType("MyArray[*,*]") or Type.GetType("MyArray[,]")

 

Lets go back to generate our mock test case for the Nested class ClientAddress.

namespace ConsoleApplicationUsePlus
{
    class Program
    {
        static void Main(string[] args)
        {
            MockHelper generator = new MockHelper();
            //Generate mock testcase
            generator.Generate();
            Console.ReadLine();
        }
    }

    class MockHelper
    {
        int index = 0;

        private void GenerateMock(object obj)
        {
            DoWork(obj, string.Empty);
        }

        Dictionary<string, string> keys = new Dictionary<string, string>();

        private void DoWork(object obj, string baseInstanceName)
        {
            Console.WriteLine(obj.GetType().ToString());
            index = index + 1;

            string instanceName = string.Format("{0}{1}", obj.GetType().Name, index);
            Console.WriteLine(String.Format("{0} {1} = new {0}(); ", obj.GetType().Name, instanceName));

            keys.Add(baseInstanceName, instanceName);

            foreach (System.Reflection.PropertyInfo property in obj.GetType().GetProperties())
            {
                if (property.PropertyType.Assembly.FullName.Contains("ConsoleApplicationUsePlus"))
                {

                    object propertyInstance = property.GetValue(obj, null);
                    if (propertyInstance == null)
                    {
                        propertyInstance = Activator.CreateInstance(property.PropertyType);
                        if (property.CanWrite)
                            property.SetValue(obj, propertyInstance, null);

                        string baseI = String.Format(@"{0}.{1}", instanceName, property.Name);
                        DoWork(propertyInstance, baseI);

                        Console.WriteLine(String.Format(@"{0}.{1} = {2} ;", instanceName, property.Name, keys[baseI]));
                    }
                }
                else if (property.PropertyType == typeof(string))
                {
                    Console.WriteLine(String.Format(@"{0}.{1} = {2} ;", instanceName, property.Name, GetRandomString()));
                }
            }
        }

        //Entry point
        public void Generate()
        {

            Assembly assembly = Assembly.GetAssembly(typeof(TheClient));
            Type type = assembly.GetType("ConsoleApplicationUsePlus.TheClient+ClientAddress"); //Notice the plus sign(+)
            object obj = Activator.CreateInstance(type);

            GenerateMock(obj);

        }

        private string GetRandomString()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 1);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

    }
}

 

and the output looks like the following.

output

 

I have discussed about the MockHelper in one of my earlier post, so not discussing this code again here.

Conclusion

We have looked at the qualified type name of nested classes, also looked at how to use Type.GetType() for various types. The best way to avoid any mistakes on the  type name possibly, is to create and instance of the class and to invoke the GetType().ToString() on the instantiated object;

Example :

TheClient.ClientAddress obj = new TheClient.ClientAddress();

Console.WriteLine(obj.GetType().ToString());

 

Enjoy Coding!!

Print | posted on Friday, November 07, 2008 7:23 PM |

Feedback

Gravatar

# re: Reflection Tips on Nested Classes: Use (+) plus instead of (.) dot with Assembly.GetType

Thanks admin nice nice post güzel oldu yani
kilo verme
manken
9/3/2009 9:51 AM | sesli sohbet
Gravatar

# re: Reflection Tips on Nested Classes: Use (+) plus instead of (.) dot with Assembly.GetType

thaaaaaanx goood admin :)
9/13/2009 5:11 AM | مسلسل باب الحاره 4
Gravatar

# re: Reflection Tips on Nested Classes: Use (+) plus instead of (.) dot with Assembly.GetType

good :) Thanks admin nice nice post güzel oldu yani
9/17/2009 6:25 AM | مقاطع
Gravatar

# re: Reflection Tips on Nested Classes: Use (+) plus instead of (.) dot with Assembly.GetType

Thanks admin nice nice post güzel oldu yani
good
9/17/2009 6:32 AM | برامج كمبيوتر
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: