4 people following this project (follow)

What is this?

The Attribute Builder builds an attribute from a lambda expression because it can.

O rly? What does it do?

It helps in reflection emit scenarios if you need to apply attributes to assemblies, modules and types.

With Attribute Builder:
// Simply use a lambda expression to express your intent
assembly.SetCustomAttribute( () => new MyAttribute("Hello worlds!", 42) );

// Map object initialization to named arguments
assembly.SetCustomAttribute( () => new MyAttribute("Hello worlds!", 42) { Property = "foo" , field = 21 } );

Without Attribute Builder:
// Intent get's lost in noisy code
var parameters = new Type[] { typeof(string), typeof(int) };
var constructor = typeof(MyAttribute).GetConstructor(parameters);
var builder = new CustomAttributeBuilder(constructor, 
    new object[] { "Hello worlds!", 42 });

// What attribute are we applying here, and how have we configured it?
assembly.SetCustomAttribute(builder);

That's it?!

No, it also preserves your original intent, so if you use CustomAttributeData to inspect the attributes you can still get ConstructorArguments and NamedArguments. This enables easier unit testing of your custom attribute classes.

No way! How did you do that?

With some extension methods and by inspecting the expression tree.

Thanks!

Your welcome!

Last edited Jan 15 at 9:09 PM by michielvoo, version 18