Geeks With Blogs

News Awarded Microsoft MVP C#.NET - 2007, 2008 and 2009


I am born in Bangladesh and currently live in Melbourne, Australia. I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net)and born in Bangladesh.
I am founder and Chief Executive Officer of
Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh. Co-founder and core developer of Pageflakes www.pageflakes.com.
Simplexhub, is on its mission to build a smart virtual community in Bangladesh and recently launched beta realestatebazaar.com.bd an ASP.NET MVC application written in C#.NET.


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
Shahed Khan blog

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!!

Posted on Friday, November 7, 2008 7:23 PM | Back to top


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

# re: Reflection Tips on Nested Classes: Use (+) plus instead of (.) dot with Assembly.GetType
Requesting Gravatar...
Thanks admin nice nice post güzel oldu yani
kilo verme
manken
Left by sesli sohbet on Sep 03, 2009 9:51 AM

# re: Reflection Tips on Nested Classes: Use (+) plus instead of (.) dot with Assembly.GetType
Requesting Gravatar...
thaaaaaanx goood admin :)
Left by مسلسل باب الحاره 4 on Sep 13, 2009 5:11 AM

# re: Reflection Tips on Nested Classes: Use (+) plus instead of (.) dot with Assembly.GetType
Requesting Gravatar...
good :) Thanks admin nice nice post güzel oldu yani
Left by مقاطع on Sep 17, 2009 6:25 AM

# re: Reflection Tips on Nested Classes: Use (+) plus instead of (.) dot with Assembly.GetType
Requesting Gravatar...
Thanks admin nice nice post güzel oldu yani
good
Left by برامج كمبيوتر on Sep 17, 2009 6:32 AM

Your comment:
 (will show your gravatar)


Copyright © Shahed Khan | Powered by: GeeksWithBlogs.net