« Home | @Software-Architect.Net EMail Launched » | Got a bike » | Back @ Blogger » | Software-Architect.net Alpha has been launched for... » | Generics.Net » 

Saturday, March 25, 2006 

Ways of Instantiation

.Net provide many ways to instantiate an object. Here I am going to enlighten some of them.

  1. When Type is loaded or available.
    This is the most basic way of instantiating an object, To instantiate and object use new keyword, following the type’s constructor.

    Object obj = new Object();

  2. When type is not loaded or available

    If you want to instantiate object dynamically when Type (class, struct, etc…) is not available or not loaded into the assembly then Activator comes at your service. You can create an instance using Activator.CreateInstance(…) and Activator.CreateInstanceFrom(…) methods. These methods provide many overloads for creating instances from various parameters. Some of examples given below.
    1. Using Type’s object:

      IObject obj = (IObject) Activator.CreateInstance( type, new object [] {"a", 10});

      Here the first parameter is an object's Type, and the second parameter is an array of arguments which are supplied to the constructor of given Type.

    2. Using Assembly and class name as string

      ObjectHandle handle = Activator.CreateInstance( "AssemblyName","NamespaceName.ClassName" );
      IObject obj = (IObject)handle.Unwrap();

      There are other overloads also please check out MSDN document…

Great

Sometime before I was looking forward for method of instantiating an object from the Type...

Keep it up

Regards
Naresh Kulkarni

Post a Comment

About me

  • I'm M. Aamir Maniar
  • From Mumbai, Maharastra, India
My profile

Archives

Powered by Blogger
and Blogger Templates