This documentation is archived and is not being maintained.

TypeBuilder.DefineProperty Method

Adds a new property to the class, with the given name and property signature.

[Visual Basic]
Public Function DefineProperty( _
   ByVal name As String, _
   ByVal attributes As PropertyAttributes, _
   ByVal returnType As Type, _
   ByVal parameterTypes() As Type _
) As PropertyBuilder
[C#]
public PropertyBuilder DefineProperty(
 string name,
 PropertyAttributes attributes,
 Type returnType,
 Type[] parameterTypes
);
[C++]
public: PropertyBuilder* DefineProperty(
 String* name,
 PropertyAttributes attributes,
 Type* returnType,
 Type* parameterTypes[]
);
[JScript]
public function DefineProperty(
   name : String,
 attributes : PropertyAttributes,
 returnType : Type,
 parameterTypes : Type[]
) : PropertyBuilder;

Parameters

name
The name of the property. name cannot contain embedded nulls.
attributes
The attributes of the property.
returnType
The return type of the property.
parameterTypes
The types of the parameters of the property.

Return Value

The defined property.

Exceptions

Exception Type Condition
ArgumentException The length of name is zero.
ArgumentNullException name is a null reference (Nothing in Visual Basic)

-or-

if any of the elements of the parameterTypes array is a null reference (Nothing)

InvalidOperationException The type was previously created using CreateType

Example

[Visual Basic, C#, C++] The following code sample demonstrates how to define a dynamic property and obtain a PropertyBuilder for specification. Note that a PropertyBuilder must also have a corresponding MethodBuilder, which will house the IL logic for the property.

[Visual Basic] 
Imports System
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit

 _

Class PropertyBuilderDemo
   
   
   
   Public Shared Function BuildDynamicTypeWithProperties() As Type
      Dim myDomain As AppDomain = Thread.GetDomain()
      Dim myAsmName As New AssemblyName()
      myAsmName.Name = "MyDynamicAssembly"
      
      Dim myAsmBuilder As AssemblyBuilder = myDomain.DefineDynamicAssembly(myAsmName, _
                            AssemblyBuilderAccess.Run)
      
      Dim myModBuilder As ModuleBuilder = myAsmBuilder.DefineDynamicModule("MyModule")
      
      Dim myTypeBuilder As TypeBuilder = myModBuilder.DefineType("CustomerData", TypeAttributes.Public)
      
      Dim customerNameBldr As FieldBuilder = myTypeBuilder.DefineField("customerName", _
                         GetType(String), FieldAttributes.Private)
      
      Dim custNamePropBldr As PropertyBuilder = myTypeBuilder.DefineProperty("CustomerName", _
                        PropertyAttributes.HasDefault, _
                        GetType(String), New Type() {GetType(String)})
      
      ' First, we'll define the behavior of the "get" property for CustomerName as a method.
      Dim custNameGetPropMthdBldr As MethodBuilder = myTypeBuilder.DefineMethod("GetCustomerName", _
                             MethodAttributes.Public, GetType(String), _
                             New Type() {})
      
      Dim custNameGetIL As ILGenerator = custNameGetPropMthdBldr.GetILGenerator()
      
      custNameGetIL.Emit(OpCodes.Ldarg_0)
      custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr)
      custNameGetIL.Emit(OpCodes.Ret)
      
      ' Now, we'll define the behavior of the "set" property for CustomerName.
      Dim custNameSetPropMthdBldr As MethodBuilder = myTypeBuilder.DefineMethod("SetCustomerName", _
                             MethodAttributes.Public, Nothing, _
                             New Type() {GetType(String)})
      
      Dim custNameSetIL As ILGenerator = custNameSetPropMthdBldr.GetILGenerator()
      
      custNameSetIL.Emit(OpCodes.Ldarg_0)
      custNameSetIL.Emit(OpCodes.Ldarg_1)
      custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr)
      custNameSetIL.Emit(OpCodes.Ret)
      
      ' Last, we must map the two methods created above to our PropertyBuilder to 
      ' their corresponding behaviors, "get" and "set" respectively. 
      custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr)
      custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr)
      
      
      Return myTypeBuilder.CreateType()
   End Function 'BuildDynamicTypeWithProperties
    
   
   
   Public Shared Sub Main()
      Dim custDataType As Type = BuildDynamicTypeWithProperties()
      
      Dim custDataPropInfo As PropertyInfo() = custDataType.GetProperties()
      Dim pInfo As PropertyInfo
      For Each pInfo In  custDataPropInfo
         Console.WriteLine("Property '{0}' created!", pInfo.ToString())
      Next pInfo
      
      Console.WriteLine("---")
      ' Note that when invoking a property, you need to use the proper BindingFlags -
      ' BindingFlags.SetProperty when you invoke the "set" behavior, and 
      ' BindingFlags.GetProperty when you invoke the "get" behavior. Also note that
      ' we invoke them based on the name we gave the property, as expected, and not
      ' the name of the methods we bound to the specific property behaviors.
      Dim custData As Object = Activator.CreateInstance(custDataType)
      custDataType.InvokeMember("CustomerName", BindingFlags.SetProperty, Nothing, _
                custData, New Object() {"Joe User"})
      
      Console.WriteLine("The customerName field of instance custData has been set to '{0}'.", _
            custDataType.InvokeMember("CustomerName", BindingFlags.GetProperty, _
            Nothing, custData, New Object() {}))
   End Sub 'Main
End Class 'PropertyBuilderDemo


' --- O U T P U T ---
' The output should be as follows:
' -------------------
' Property 'System.String CustomerName [System.String]' created!
' ---
' The customerName field of instance custData has been set to 'Joe User'.
' -------------------

[C#] 

using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;

class PropertyBuilderDemo

{

   public static Type BuildDynamicTypeWithProperties() 
   {
    AppDomain myDomain = Thread.GetDomain();
    AssemblyName myAsmName = new AssemblyName();
    myAsmName.Name = "MyDynamicAssembly";

    AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(myAsmName,
                            AssemblyBuilderAccess.Run);

    ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule("MyModule");

    TypeBuilder myTypeBuilder = myModBuilder.DefineType("CustomerData", 
                            TypeAttributes.Public);

    FieldBuilder customerNameBldr = myTypeBuilder.DefineField("customerName",
                            typeof(string),
                            FieldAttributes.Private);

    PropertyBuilder custNamePropBldr = myTypeBuilder.DefineProperty("CustomerName",
                             PropertyAttributes.HasDefault,
                             typeof(string),
                             new Type[] { typeof(string) });

    // First, we'll define the behavior of the "get" property for CustomerName as a method.
    MethodBuilder custNameGetPropMthdBldr = myTypeBuilder.DefineMethod("GetCustomerName",
                            MethodAttributes.Public,    
                            typeof(string),
                            new Type[] { });

    ILGenerator custNameGetIL = custNameGetPropMthdBldr.GetILGenerator();

    custNameGetIL.Emit(OpCodes.Ldarg_0);
    custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
    custNameGetIL.Emit(OpCodes.Ret);

    // Now, we'll define the behavior of the "set" property for CustomerName.
    MethodBuilder custNameSetPropMthdBldr = myTypeBuilder.DefineMethod("SetCustomerName",
                            MethodAttributes.Public,    
                            null,
                            new Type[] { typeof(string) });

    ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();

    custNameSetIL.Emit(OpCodes.Ldarg_0);
    custNameSetIL.Emit(OpCodes.Ldarg_1);
    custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
    custNameSetIL.Emit(OpCodes.Ret);

    // Last, we must map the two methods created above to our PropertyBuilder to 
    // their corresponding behaviors, "get" and "set" respectively. 
    custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
    custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);


    return myTypeBuilder.CreateType();    


   }

   public static void Main() 
   {
    Type custDataType = BuildDynamicTypeWithProperties();
    
    PropertyInfo[] custDataPropInfo = custDataType.GetProperties();
    foreach (PropertyInfo pInfo in custDataPropInfo) {
       Console.WriteLine("Property '{0}' created!", pInfo.ToString());
    }

    Console.WriteLine("---");
    // Note that when invoking a property, you need to use the proper BindingFlags -
    // BindingFlags.SetProperty when you invoke the "set" behavior, and 
    // BindingFlags.GetProperty when you invoke the "get" behavior. Also note that
    // we invoke them based on the name we gave the property, as expected, and not
    // the name of the methods we bound to the specific property behaviors.

    object custData = Activator.CreateInstance(custDataType);
    custDataType.InvokeMember("CustomerName", BindingFlags.SetProperty,
                      null, custData, new object[]{ "Joe User" });

    Console.WriteLine("The customerName field of instance custData has been set to '{0}'.",
               custDataType.InvokeMember("CustomerName", BindingFlags.GetProperty,
                              null, custData, new object[]{ }));
   }

}

// --- O U T P U T ---
// The output should be as follows:
// -------------------
// Property 'System.String CustomerName [System.String]' created!
// ---
// The customerName field of instance custData has been set to 'Joe User'.
// -------------------


[C++] 

#using <mscorlib.dll>

using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;

Type* BuildDynamicTypeWithProperties() {
   AppDomain*  myDomain = Thread::GetDomain();
   AssemblyName* myAsmName = new AssemblyName();
   myAsmName->Name = S"MyDynamicAssembly";

   AssemblyBuilder*  myAsmBuilder = myDomain->DefineDynamicAssembly(
      myAsmName,
      AssemblyBuilderAccess::Run);

   ModuleBuilder*  myModBuilder = myAsmBuilder->DefineDynamicModule(S"MyModule");

   TypeBuilder*  myTypeBuilder = myModBuilder->DefineType(
      S"CustomerData",
      TypeAttributes::Public);

   FieldBuilder*  customerNameBldr = myTypeBuilder->DefineField(
      S"customerName",
      __typeof(String),
      FieldAttributes::Private);

   Type* temp0 [] = {__typeof(String)};
   PropertyBuilder*  custNamePropBldr = myTypeBuilder->DefineProperty(
      S"CustomerName",
      PropertyAttributes::HasDefault,
      __typeof(String),
      temp0);

   // First, we'll define the behavior of the "get" property for CustomerName as a method.
   MethodBuilder*  custNameGetPropMthdBldr = myTypeBuilder->DefineMethod(
      S"GetCustomerName",
      MethodAttributes::Public,
      __typeof(String),
      new Type*[0]);

   ILGenerator*  custNameGetIL = custNameGetPropMthdBldr->GetILGenerator();

   custNameGetIL->Emit(OpCodes::Ldarg_0);
   custNameGetIL->Emit(OpCodes::Ldfld, customerNameBldr);
   custNameGetIL->Emit(OpCodes::Ret);

   // Now, we'll define the behavior of the "set" property for CustomerName.

   Type* temp2 [] = {__typeof(String)};
   MethodBuilder*  custNameSetPropMthdBldr = myTypeBuilder->DefineMethod(
      S"SetCustomerName",
      MethodAttributes::Public,
      0,
      temp2);

   ILGenerator*  custNameSetIL = custNameSetPropMthdBldr->GetILGenerator();

   custNameSetIL->Emit(OpCodes::Ldarg_0);
   custNameSetIL->Emit(OpCodes::Ldarg_1);
   custNameSetIL->Emit(OpCodes::Stfld, customerNameBldr);
   custNameSetIL->Emit(OpCodes::Ret);

   // Last, we must map the two methods created above to our PropertyBuilder to
   // their corresponding behaviors, "get" and "set" respectively.
   custNamePropBldr->SetGetMethod(custNameGetPropMthdBldr);
   custNamePropBldr->SetSetMethod(custNameSetPropMthdBldr);

   return myTypeBuilder->CreateType();
}

int main() {
   Type*  custDataType = BuildDynamicTypeWithProperties();

   PropertyInfo*  custDataPropInfo[] = custDataType->GetProperties();
   System::Collections::IEnumerator* myEnum = custDataPropInfo->GetEnumerator();
   while (myEnum->MoveNext()) {
      PropertyInfo* pInfo = __try_cast<PropertyInfo*>(myEnum->Current);
      Console::WriteLine(S"Property '{0}' created!", pInfo);
   }

   Console::WriteLine(S"---");
   // Note that when invoking a property, you need to use the proper BindingFlags -
   // BindingFlags::SetProperty when you invoke the "set" behavior, and
   // BindingFlags::GetProperty when you invoke the "get" behavior. Also note that
   // we invoke them based on the name we gave the property, as expected, and not
   // the name of the methods we bound to the specific property behaviors.

   Object* custData = Activator::CreateInstance(custDataType);

   Object* temp3 [] = {S"Joe User"};
   custDataType->InvokeMember(S"CustomerName", BindingFlags::SetProperty,
      0, custData, temp3);

   Console::WriteLine(S"The customerName field of instance custData has been set to '{0}'.",
      custDataType->InvokeMember(S"CustomerName", BindingFlags::GetProperty,
      0, custData, new Object*[0]));
}
// --- O U T P U T ---
// The output should be as follows:
// -------------------
// Property 'System.String CustomerName [System.String]' created!
// ---
// The customerName field of instance custData has been set to 'Joe User'.
// -------------------

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

TypeBuilder Class | TypeBuilder Members | System.Reflection.Emit Namespace

Show: