Share via


FieldBuilder.SetCustomAttribute Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Sets a custom attribute using a custom attribute builder.

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

Syntax

'Declaration
<SecuritySafeCriticalAttribute> _
Public Sub SetCustomAttribute ( _
    customBuilder As CustomAttributeBuilder _
)
[SecuritySafeCriticalAttribute]
public void SetCustomAttribute(
    CustomAttributeBuilder customBuilder
)

Parameters

Exceptions

Exception Condition
ArgumentNullException

con is nulla null reference (Nothing in Visual Basic).

InvalidOperationException

The parent type of this field is complete.

Examples

The following code sample illustrates the use of SetCustomAttribute in the context of FieldBuilder, using a CustomAttributeBuilder.

Imports System.Reflection
Imports System.Reflection.Emit

<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)> _
Public Class MyAttribute
    Inherits Attribute
    Private myStringValue As String

    Public ReadOnly Property MyString As String
        Get
            Return myStringValue 
        End Get
    End Property

    Public Sub New(ByVal myString As String)
        myStringValue = myString
    End Sub 
End Class 

Public Class Example

    Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

        ' Create a name for the assembly.
        Dim myAssemblyName As New AssemblyName("EmittedAssembly")
        ' Create the dynamic assembly in the current application domain.
        Dim myAssemblyBuilder As AssemblyBuilder = _
              AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName, _
                    AssemblyBuilderAccess.Run)
        Dim myModuleBuilder As ModuleBuilder = _
              myAssemblyBuilder.DefineDynamicModule("EmittedModule")
        ' Define a public class named 'CustomClass' in the assembly.
        Dim myTypeBuilder As TypeBuilder = myModuleBuilder.DefineType("CustomClass", _
                                               TypeAttributes.Public)

        ' Define a private String field named 'MyField' in the type.
        Dim myFieldBuilder As FieldBuilder = myTypeBuilder.DefineField("MyField", _
                                       GetType(String), FieldAttributes.Public)

        ' To set a custom attribute, first get the constructor for the attribute.
        ' Use the constructor and an array of arguments for the constructor to
        ' create a CustomAttributeBuilder. Finally, use the CustomAttributeBuilder
        ' to set the attribute on the enumeration. 
        Dim myAttributeType As Type = GetType(MyAttribute)
        Dim myConstructorInfo As ConstructorInfo = _
                     myAttributeType.GetConstructor(New Type() {GetType(String)})
        Dim attributeBuilder As _
            New CustomAttributeBuilder(myConstructorInfo, New Object() {"Test"})
        myFieldBuilder.SetCustomAttribute(attributeBuilder)

         Try
        Dim myCustomClass As Type = myTypeBuilder.CreateType()

        ' Retrieve the values of Attributes applied to field and display them.
        Dim myFieldInfo As FieldInfo = myCustomClass.GetField("MyField")
        For Each attr As Object In myFieldInfo.GetCustomAttributes(True)

            outputBlock.Text &= attr.ToString() & vbCrLf
            If TypeOf attr Is MyAttribute Then
                outputBlock.Text &= String.Format("    MyString: {0}" & vbCrLf, _
                    CType(attr, MyAttribute).MyString.ToString())
            End If
        Next
         Catch e As Exception
            outputBlock.Text &= "Exception Caught " + e.Message & vbCrLf
        End Try
    End Sub 
End Class 

' This example produces output similar to the following:
'
'SilverlightApplication.MyAttribute
'    MyString: Test
using System;
using System.Reflection;
using System.Reflection.Emit;

[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class MyAttribute : Attribute
{
    private string myStringValue;

    public string MyString { get { return myStringValue; }}   

    public MyAttribute(string myString)
    {
        myStringValue = myString;
    }
}

class Example
{
    public static void Demo(System.Windows.Controls.TextBlock outputBlock)
    {
        // Create a simple name for the assembly.
        AssemblyName myAssemblyName = new AssemblyName("EmittedAssembly");
        // Create the dynamic assembly.
        AssemblyBuilder myAssemblyBuilder =
            AppDomain.CurrentDomain.DefineDynamicAssembly(
                myAssemblyName, AssemblyBuilderAccess.Run);
        ModuleBuilder myModuleBuilder =
                 myAssemblyBuilder.DefineDynamicModule("EmittedModule");
        // Define a public class named 'CustomClass' in the assembly.
        TypeBuilder myTypeBuilder = myModuleBuilder.DefineType("CustomClass",
            TypeAttributes.Public);

        // Define a private String field named 'MyField' in the type.
        FieldBuilder myFieldBuilder =
            myTypeBuilder.DefineField("MyField", typeof(String), FieldAttributes.Public);

        // To set a custom attribute, first get the constructor for the attribute.
        // Use the constructor and an array of arguments for the constructor to
        // create a CustomAttributeBuilder. Finally, use the CustomAttributeBuilder
        // to set the attribute on the enumeration. 
        Type myAttributeType = typeof(MyAttribute);
        ConstructorInfo myConstructorInfo = 
            myAttributeType.GetConstructor(new Type[] { typeof(string) });
        CustomAttributeBuilder attributeBuilder =
            new CustomAttributeBuilder(myConstructorInfo, new object[] { "Test" });
        myFieldBuilder.SetCustomAttribute(attributeBuilder);

        Type myCustomClass = myTypeBuilder.CreateType();
        // Retrieve the values of Attributes applied to field and display to console.
        FieldInfo myFieldInfo = myCustomClass.GetField("MyField");
        foreach (object attr in myFieldInfo.GetCustomAttributes(true))
        {
            outputBlock.Text += attr.ToString() + "\n";
            if (attr is MyAttribute)
            {
                outputBlock.Text += String.Format("    MyString: {0}\n",
                    ((MyAttribute) attr).MyString.ToString());
            }
        }
    }
}

/* This example produces output similar to the following:

MyAttribute
    MyString: Test
 */

Version Information

Silverlight

Supported in: 5, 4, 3

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.