Skip to content

Instantly share code, notes, and snippets.

@AlbertoMonteiro
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlbertoMonteiro/05aadce7ad2a2bef912b to your computer and use it in GitHub Desktop.
Save AlbertoMonteiro/05aadce7ad2a2bef912b to your computer and use it in GitHub Desktop.
Dynamically adding attribute in a property
var type = typeof(Teste);
var assemblyName = new AssemblyName("TesteNamespace");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
var typeBuilder = moduleBuilder.DefineType("TesteNamespace." + type.Name + "Proxy", TypeAttributes.Public, type);
var jsonIgnoreType = typeof(JsonIgnoreAttribute);
var constructorInfo = jsonIgnoreType.GetConstructor(Type.EmptyTypes);
var attributeBuilder = new CustomAttributeBuilder(constructorInfo, Type.EmptyTypes);
var propertyBuilder = typeBuilder.DefineProperty("Nascimento", PropertyAttributes.None, typeof(DateTime), Type.EmptyTypes);
propertyBuilder.SetCustomAttribute(attributeBuilder);
const MethodAttributes METHOD_ATTRIBUTES = MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
var pGet = typeBuilder.DefineMethod("get_Nascimento", METHOD_ATTRIBUTES, typeof(DateTime), Type.EmptyTypes);
var pILGet = pGet.GetILGenerator();
//You must write get method code, this is just a demonstration how to do it
pILGet.Emit(OpCodes.Ret);
var pSet = typeBuilder.DefineMethod("set_Nascimento", METHOD_ATTRIBUTES, null, new[] { typeof(DateTime) });
var pILSet = pSet.GetILGenerator();
//You must write set method code, this is just a demonstration how to do it
pILSet.Emit(OpCodes.Ret);
propertyBuilder.SetSetMethod(pSet);
propertyBuilder.SetGetMethod(pGet);
var newType = typeBuilder.CreateType();

How to dynamically add attribute in a property from some class

  1. First you need a class
  2. Make the property virtual
  3. Create a new type that inherits from your base type
  4. Create a property
  5. Set the attribute
  6. Be happy ;D

In this sample I added a JsonIgnore attribute to my property

Base class:

public class Teste
{
    public virtual DateTime Nascimento { get; set; }
    public decimal Valor { get; set; }
}

Result after IL Weaving:

public class TesteProxy : Teste
{
    [JsonIgnore]
    public virtual DateTime Nascimento { get; set; }
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment