Type Instantiating

In this chapter you will learn:

  1. Instantiating Types
  2. Instantiate generic types

Instantiating Types

There are two ways to dynamically instantiate an object from its type:

  • Call Activator.CreateInstance method
  • Call Invoke on a ConstructorInfo object obtained from a Type

Activator.CreateInstance accepts a Type and optional arguments that get passed to the constructor:

using System;//from  j a v  a2  s . c o m
using System.Reflection;
using System.Collections.Generic;

class MainClass
{
    static void Main()
    {
        int i = (int)Activator.CreateInstance(typeof(int));

        DateTime dt = (DateTime)Activator.CreateInstance(typeof(DateTime),2000, 1, 1);

    }

}

Instantiate generic types

To dynamically instantiate a delegate, call Delegate.CreateDelegate. The following example demonstrates instantiating both an instance delegate and a static delegate:

using System;// java2  s  . c  om
using System.Reflection;
using System.Collections.Generic;

class Program
{
    delegate int IntFunc(int x);

    static int Square(int x) { return x * x; }  // Static method 
    int  Cube  (int x) { return x * x * x; } // Instance method

    static void Main()
    {
        Delegate staticD = Delegate.CreateDelegate(typeof(IntFunc), typeof(Program), "Square");

        Delegate instanceD = Delegate.CreateDelegate
        (typeof(IntFunc), new Program(), "Cube");
        Console.WriteLine(staticD.DynamicInvoke(3));  // 9
        Console.WriteLine(instanceD.DynamicInvoke(3));  // 27
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to get interfaces from Type
  2. static and dynamic interface type checking
  3. Get all implemented interface and their methods
Home » C# Tutorial » Reflection
Reflection
Type
Type properties
Field reflection
Field Type
Field Attributes
FieldHandle
Field value
Set Field value
delegate reflection
Event reflection
Indexer reflection
Properties Reflection
Method
Parameter
Invoke
Type Instantiating
interface reflection
Generic type reflection
Reflection on nested Types
Subtype
Array reflection
Assembly