Tuesday, May 25, 2010

Creating Object to a Class dynamically using Reflection

What is Reflection?

Reflection is the feature in .Net, which enables us to get some information about object in run time. That information contains data of the class. Also it can get the names of the methods that are inside the class and constructors of that object.

To write a C# .Net program which uses reflection, the program should use the namespace System.Reflection. To get type of the object, the typeof operator can be used. There is one more method GetType(). This also can be used for retrieving the type information of a class. The Operator typeof allow us to get class name of our object and GetType() method uses to get data about object's type.

One can use the Activator class for creating objects and then you can use reflection to call methods on the new instance, e.g.:

Example-1: C#
In this example simply show that how to create instance of a object dynamically,

using System;
using System.Runtime.Remoting;
using System.Reflection;
namespace ConsoleApplication3
{
interface IBase
{
void fu();
}
class Emp: IBase
{
public void fu()
{
Console.Write("Hello");
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Type type = Type.GetType("ConsoleApplication3.Emp");
IBase obj = (IBase)Activator.CreateInstance(type);
obj.fu();
}
}


Example-2: C#
In this example just show that how to create instance of a object dynamically and GET and SET the property value at runtime.

using System;
using System.Runtime.Remoting;
using System.Reflection;

namespace SampleApp
{
public class Person
{
private string name = string.Empty;

public Person()
{
}
public string Name
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
object obj = ((ObjectHandle)Activator.CreateInstance(null, "SampleApp.Person")).Unwrap();
Type type = obj.GetType();
type.GetProperty("Name").SetValue(obj,"Hello World", null);
string personName = type.GetProperty("Name").GetValue(obj, null).ToString();

Console.WriteLine(personName);
Console.ReadLine();
}
}
}

No comments:

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...