Code :
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
class PropertyBuilderDemo
{
public static Type BuildProperties()
{
AppDomain _Domain = Thread.GetDomain();
AssemblyName _AssemblyName = new AssemblyName();
_AssemblyName.Name = "DynamicAssembly";
AssemblyBuilder _AssemblyBuilder = _Domain.DefineDynamicAssembly(_AssemblyName,AssemblyBuilderAccess.RunAndSave);
ModuleBuilder _ModuleBuilder = _AssemblyBuilder.DefineDynamicModule("DynamicModule");
TypeBuilder _TypeBuilder = _ModuleBuilder.DefineType("CustomerData",TypeAttributes.Public);
FieldBuilder _customerName = _TypeBuilder.DefineField("_CustomerName",typeof(string),FieldAttributes.Private);
PropertyBuilder _CustomerName = _TypeBuilder.DefineProperty("CustomerName",PropertyAttributes.HasDefault,typeof(string),new Type[] { typeof(string) });
//Assigning 'Get' Behavior to Customer Name Property
MethodBuilder _GetCustomerName = _TypeBuilder.DefineMethod("GetCustomerName",MethodAttributes.Public,typeof(string),new Type[] { });
ILGenerator _GetILGenerator = _GetCustomerName.GetILGenerator();
_GetILGenerator.Emit(OpCodes.Ldarg_0);
_GetILGenerator.Emit(OpCodes.Ldfld,_customerName);
_GetILGenerator.Emit(OpCodes.Ret);
//Assigning 'Set' Behavior to Customer Name Property
MethodBuilder _SetCustomerName = _TypeBuilder.DefineMethod("SetCustomerName",MethodAttributes.Public,null,new Type[] { typeof(string) });
ILGenerator _SetILGenerator = _SetCustomerName.GetILGenerator();
_SetILGenerator.Emit(OpCodes.Ldarg_0);
_SetILGenerator.Emit(OpCodes.Ldarg_1);
_SetILGenerator.Emit(OpCodes.Stfld,_customerName);
_SetILGenerator.Emit(OpCodes.Ret);
//Attaching Get and Set behaviors to property
_CustomerName.SetGetMethod(_GetCustomerName);
_CustomerName.SetSetMethod(_SetCustomerName);
return _TypeBuilder.CreateType();
}
}
///Client Code
static void Main(string[] args)
{
Type customer = PropertyBuilderDemo.BuildProperties();
PropertyInfo[] properties = customer.GetProperties();
object customerData = Activator.CreateInstance(customer);
properties[0].SetValue(customerData,"CREATED BY : Kaushal Patel",BindingFlags.SetProperty,null,null,null);
string s = properties[0].GetValue(customerData,BindingFlags.GetProperty,null,null,null).ToString();
Console.WriteLine(s.ToString());
Console.ReadLine();
}
4 More Information Do Mail Me @ mail2kaushal@gmail.com