Type Instantiating
In this chapter you will learn:
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:
- How to get interfaces from Type
- static and dynamic interface type checking
- Get all implemented interface and their methods
Home » C# Tutorial » Reflection