Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an attribute to another assembly's class

Tags:

c#

attributes

Is it somehow possible to extend a type, wich is defined in another assembly, to add an attribute on one of its properties?

Exemple I have in assembly FooBar:

public class Foo
{
   public string Bar { get; set; }
}

But in my UI assembly, I want to pass this type to a third party tool, and for this third party tool to work correctly I need the Bar property to have a specific attribute. This attribute is defined in the third party assembly, and I don't want a reference to this assembly in my FooBar assembly, since FooBar contains my domain an this is a UI tool.

like image 662
Johnny5 Avatar asked Nov 29 '11 19:11

Johnny5


2 Answers

You can't, if the thirdy-party tool uses standard reflection to get the attributes for your type.

You can, if the third-party tool uses the TypeDescriptor API to get the attributes for your type.

Sample code for the type descriptor case:

public class Foo
{
    public string Bar { get; set; }
}

class FooMetadata
{
    [Display(Name = "Bar")]
    public string Bar { get; set; }
}

static void Main(string[] args)
{
    PropertyDescriptorCollection properties;

    AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider;

    properties = TypeDescriptor.GetProperties(typeof(Foo));
    Console.WriteLine(properties[0].Attributes.Count); // Prints X

    typeDescriptionProvider = new AssociatedMetadataTypeTypeDescriptionProvider(
        typeof(Foo),
        typeof(FooMetadata));

    TypeDescriptor.AddProviderTransparent(typeDescriptionProvider, typeof(Foo));

    properties = TypeDescriptor.GetProperties(typeof(Foo));
    Console.WriteLine(properties[0].Attributes.Count); // Prints X+1
}

If you run this code you'll see that last console write prints plus one attribute because the Display attribute is now also being considered.

like image 125
João Angelo Avatar answered Sep 30 '22 12:09

João Angelo


No. It's not possible to add attributes to types from separate assemblies.

What you can do, though, is create your own type that wraps the third-party type. Since you have full control over your wrapper class, you can add the attributes there.

like image 32
Justin Niessner Avatar answered Sep 30 '22 13:09

Justin Niessner