Export (0) Print
Expand All

PropertyBuilder Class

Defines the properties for a type.

Namespace:  System.Reflection.Emit
Assembly:  mscorlib (in mscorlib.dll)

[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public sealed class PropertyBuilder : PropertyInfo, 
	_PropertyBuilder

The PropertyBuilder type exposes the following members.

  NameDescription
Public propertyAttributesGets the attributes for this property. (Overrides PropertyInfo.Attributes.)
Public propertyCanReadGets a value indicating whether the property can be read. (Overrides PropertyInfo.CanRead.)
Public propertyCanWriteGets a value indicating whether the property can be written to. (Overrides PropertyInfo.CanWrite.)
Public propertyCustomAttributesGets a collection that contains this member's custom attributes. (Inherited from MemberInfo.)
Public propertyDeclaringTypeGets the class that declares this member. (Overrides MemberInfo.DeclaringType.)
Public propertyGetMethodGets the get accessor for this property. (Inherited from PropertyInfo.)
Public propertyIsSpecialNameGets a value indicating whether the property is the special name. (Inherited from PropertyInfo.)
Public propertyMemberTypeGets a MemberTypes value indicating that this member is a property. (Inherited from PropertyInfo.)
Public propertyMetadataTokenGets a value that identifies a metadata element. (Inherited from MemberInfo.)
Public propertyModuleGets the module in which the type that declares the current property is being defined. (Overrides MemberInfo.Module.)
Public propertyNameGets the name of this member. (Overrides MemberInfo.Name.)
Public propertyPropertyTokenRetrieves the token for this property.
Public propertyPropertyTypeGets the type of the field of this property. (Overrides PropertyInfo.PropertyType.)
Public propertyReflectedTypeGets the class object that was used to obtain this instance of MemberInfo. (Overrides MemberInfo.ReflectedType.)
Public propertySetMethodGets the set accessor for this property. (Inherited from PropertyInfo.)
Top

  NameDescription
Public methodAddOtherMethodAdds one of the other methods associated with this property.
Public methodEqualsReturns a value that indicates whether this instance is equal to a specified object. (Inherited from PropertyInfo.)
Public methodGetAccessors()Returns an array whose elements reflect the public get, set, and other accessors of the property reflected by the current instance. (Inherited from PropertyInfo.)
Public methodGetAccessors(Boolean)Returns an array of the public and non-public get and set accessors on this property. (Overrides PropertyInfo.GetAccessors(Boolean).)
Public methodGetConstantValueReturns a literal value associated with the property by a compiler. (Inherited from PropertyInfo.)
Public methodGetCustomAttributes(Boolean)Returns an array of all the custom attributes for this property. (Overrides MemberInfo.GetCustomAttributes(Boolean).)
Public methodGetCustomAttributes(Type, Boolean)Returns an array of custom attributes identified by Type. (Overrides MemberInfo.GetCustomAttributes(Type, Boolean).)
Public methodGetCustomAttributesDataReturns a list of CustomAttributeData objects representing data about the attributes that have been applied to the target member. (Inherited from MemberInfo.)
Public methodGetGetMethod()Returns the public get accessor for this property. (Inherited from PropertyInfo.)
Public methodGetGetMethod(Boolean)Returns the public and non-public get accessor for this property. (Overrides PropertyInfo.GetGetMethod(Boolean).)
Public methodGetHashCodeReturns the hash code for this instance. (Inherited from PropertyInfo.)
Public methodGetIndexParametersReturns an array of all the index parameters for the property. (Overrides PropertyInfo.GetIndexParameters().)
Public methodGetOptionalCustomModifiersReturns an array of types representing the optional custom modifiers of the property. (Inherited from PropertyInfo.)
Public methodGetRawConstantValueReturns a literal value associated with the property by a compiler. (Inherited from PropertyInfo.)
Public methodGetRequiredCustomModifiersReturns an array of types representing the required custom modifiers of the property. (Inherited from PropertyInfo.)
Public methodGetSetMethod()Returns the public set accessor for this property. (Inherited from PropertyInfo.)
Public methodGetSetMethod(Boolean)Returns the set accessor for this property. (Overrides PropertyInfo.GetSetMethod(Boolean).)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetValue(Object)Returns the property value of a specified object. (Inherited from PropertyInfo.)
Public methodGetValue(Object, Object[])Gets the value of the indexed property by calling the property's getter method. (Overrides PropertyInfo.GetValue(Object, Object[]).)
Public methodGetValue(Object, BindingFlags, Binder, Object[], CultureInfo)Gets the value of a property having the specified binding, index, and CultureInfo. (Overrides PropertyInfo.GetValue(Object, BindingFlags, Binder, Object[], CultureInfo).)
Public methodIsDefinedIndicates whether one or more instance of attributeType is defined on this property. (Overrides MemberInfo.IsDefined(Type, Boolean).)
Public methodSetConstantSets the default value of this property.
Public methodSetCustomAttribute(CustomAttributeBuilder)Set a custom attribute using a custom attribute builder.
Public methodSetCustomAttribute(ConstructorInfo, Byte[])Set a custom attribute using a specified custom attribute blob.
Public methodSetGetMethodSets the method that gets the property value.
Public methodSetSetMethodSets the method that sets the property value.
Public methodSetValue(Object, Object)Sets the property value of a specified object. (Inherited from PropertyInfo.)
Public methodSetValue(Object, Object, Object[])Sets the value of the property with optional index values for index properties. (Overrides PropertyInfo.SetValue(Object, Object, Object[]).)
Public methodSetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)Sets the property value for the given object to the given value. (Overrides PropertyInfo.SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo).)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public Extension MethodGetCustomAttribute(Type)Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttribute(Type, Boolean)Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttribute<T>()Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttribute<T>(Boolean)Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttributes()Overloaded. Retrieves a collection of custom attributes that are applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttributes(Type)Overloaded. Retrieves a collection of custom attributes of a specified type that are applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttributes<T>()Overloaded. Retrieves a collection of custom attributes of a specified type that are applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttributes<T>(Boolean)Overloaded. Retrieves a collection of custom attributes of a specified type that are applied to a specified member, and optionally inspects the ancestors of that member. (Defined by CustomAttributeExtensions.)
Public Extension MethodIsDefinedIndicates whether custom attributes of a specified type are applied to a specified member. (Defined by CustomAttributeExtensions.)
Top

  NameDescription
Explicit interface implemetationPrivate method_MemberInfo.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from MemberInfo.)
Explicit interface implemetationPrivate method_MemberInfo.GetTypeGets a Type object representing the MemberInfo class. (Inherited from MemberInfo.)
Explicit interface implemetationPrivate method_MemberInfo.GetTypeInfoRetrieves the type information for an object, which can then be used to get the type information for an interface. (Inherited from MemberInfo.)
Explicit interface implemetationPrivate method_MemberInfo.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from MemberInfo.)
Explicit interface implemetationPrivate method_MemberInfo.InvokeProvides access to properties and methods exposed by an object. (Inherited from MemberInfo.)
Explicit interface implemetationPrivate method_PropertyBuilder.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers.
Explicit interface implemetationPrivate method_PropertyBuilder.GetTypeInfoRetrieves the type information for an object, which can then be used to get the type information for an interface.
Explicit interface implemetationPrivate method_PropertyBuilder.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1).
Explicit interface implemetationPrivate method_PropertyBuilder.InvokeProvides access to properties and methods exposed by an object.
Explicit interface implemetationPrivate method_PropertyInfo.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from PropertyInfo.)
Explicit interface implemetationPrivate method_PropertyInfo.GetTypeGets a Type object representing the PropertyInfo type. (Inherited from PropertyInfo.)
Explicit interface implemetationPrivate method_PropertyInfo.GetTypeInfoRetrieves the type information for an object, which can then be used to get the type information for an interface. (Inherited from PropertyInfo.)
Explicit interface implemetationPrivate method_PropertyInfo.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from PropertyInfo.)
Explicit interface implemetationPrivate method_PropertyInfo.InvokeProvides access to properties and methods exposed by an object. (Inherited from PropertyInfo.)
Top

A PropertyBuilder is always associated with a TypeBuilder. The TypeBuilder. DefineProperty method will return a new PropertyBuilder to a client.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following code sample demonstrates how to implement properties in a dynamic type using a PropertyBuilder obtained via TypeBuilder.DefineProperty to create the property framework and an associated MethodBuilder to implement the IL logic within the property.


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";

        // To generate a persistable assembly, specify AssemblyBuilderAccess.RunAndSave.
        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(myAsmName,
                                                        AssemblyBuilderAccess.RunAndSave);
        // Generate a persistable single-module assembly.
        ModuleBuilder myModBuilder = 
            myAsmBuilder.DefineDynamicModule(myAsmName.Name, myAsmName.Name + ".dll");

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

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

        // The last argument of DefineProperty is null, because the 
        // property has no parameters. (If you don't specify null, you must 
        // specify an array of Type objects. For a parameterless property, 
        // use an array with no elements: new Type[] {})
        PropertyBuilder custNamePropBldr = myTypeBuilder.DefineProperty("CustomerName",
                                                         PropertyAttributes.HasDefault,
                                                         typeof(string),
                                                         null);

        // The property set and property get methods require a special 
        // set of attributes.
        MethodAttributes getSetAttr = 
            MethodAttributes.Public | MethodAttributes.SpecialName |
                MethodAttributes.HideBySig;

        // Define the "get" accessor method for CustomerName.
        MethodBuilder custNameGetPropMthdBldr = 
            myTypeBuilder.DefineMethod("get_CustomerName",
                                       getSetAttr,        
                                       typeof(string),
                                       Type.EmptyTypes);

        ILGenerator custNameGetIL = custNameGetPropMthdBldr.GetILGenerator();

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

        // Define the "set" accessor method for CustomerName.
        MethodBuilder custNameSetPropMthdBldr = 
            myTypeBuilder.DefineMethod("set_CustomerName",
                                       getSetAttr,     
                                       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);


        Type retval = myTypeBuilder.CreateType();

        // Save the assembly so it can be examined with Ildasm.exe, 
        // or referenced by a test program.
        myAsmBuilder.Save(myAsmName.Name + ".dll");
        return retval;
   }

   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'. 
// -------------------

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft