Jon Turner
Jon Turner

Reputation: 2982

Can attributes be added dynamically in C#?

Is it possible to add attributes at runtime or to change the value of an attribute at runtime?

Upvotes: 155

Views: 116383

Answers (10)

When faced with this situation, yet another solution might be questioning you code design and search for a more object-oriented way. For me, struggling with unpleasant reflection work arounds is the last resort. And my first reaction to this situation would be re-designing the code. Think of the following code, which tries to solve the problem that you have to add an attribute to a third-party class you are using.

class Employee {} // This one is third-party.

And you have code like

var specialEmployee = new Employee();
// Here you need an employee with a special behaviour and 
// want to add an attribute to the employee but you cannot.

The solution might be extracting a class inheriting from the Employee class and decorating it with your attribute:

[SpecialAttribute]
class SpecialEmployee : Employee 
{
}

When you create an instance of this new class

var specialEmployee = new SpecialEmployee();

you can distinguish this specialEmployee object from other employee objects. If appropriate, you may want to make this SpecialEmployee a private nested class.

Upvotes: 0

Eric Ouellet
Eric Ouellet

Reputation: 11753

Like mentionned in a comment below by Deczaloth, I think that metadata is fixed at compile time. I achieve it by creating a dynamic object where I override GetType() or use GetCustomType() and writing my own type. Using this then you could...

I tried very hard with System.ComponentModel.TypeDescriptor without success. That does not means it can't work but I would like to see code for that.

In counter part, I wanted to change some Attribute values. I did 2 functions which work fine for that purpose.

        // ************************************************************************
        public static void SetObjectPropertyDescription(this Type typeOfObject, string propertyName,  string description)
        {
            PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];
            var att = pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
            if (att != null)
            {
                var fieldDescription = att.GetType().GetField("description", BindingFlags.NonPublic | BindingFlags.Instance);
                if (fieldDescription != null)
                {
                    fieldDescription.SetValue(att, description);
                }
            }
        }

        // ************************************************************************
        public static void SetPropertyAttributReadOnly(this Type typeOfObject, string propertyName, bool isReadOnly)
        {
            PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];
            var att = pd.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
            if (att != null)
            {
                var fieldDescription = att.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
                if (fieldDescription != null)
                {
                    fieldDescription.SetValue(att, isReadOnly);
                }
            }
        }

Upvotes: 1

Mark Cidade
Mark Cidade

Reputation: 100047

Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the System.Type class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.

Upvotes: 71

torial
torial

Reputation: 13121

Well, just to be different, I found an article that references using Reflection.Emit to do so.

Here's the link: http://www.codeproject.com/KB/cs/dotnetattributes.aspx , you will also want to look into some of the comments at the bottom of the article, because possible approaches are discussed.

Upvotes: 11

Alex Lyman
Alex Lyman

Reputation: 15975

This really depends on what exactly you're trying to accomplish.

The System.ComponentModel.TypeDescriptor stuff can be used to add attributes to types, properties and object instances, and it has the limitation that you have to use it to retrieve those properties as well. If you're writing the code that consumes those attributes, and you can live within those limitations, then I'd definitely suggest it.

As far as I know, the PropertyGrid control and the visual studio design surface are the only things in the BCL that consume the TypeDescriptor stuff. In fact, that's how they do about half the things they really need to do.

Upvotes: 73

Keith
Keith

Reputation: 155872

Why do you need to? Attributes give extra information for reflection, but if you externally know which properties you want you don't need them.

You could store meta data externally relatively easily in a database or resource file.

Upvotes: 3

Darren Kopp
Darren Kopp

Reputation: 77667

If you need something to be able to added dynamically, c# attributes aren't the way. Look into storing the data in xml. I recently did a project that i started w/ attributes, but eventually moved to serialization w/ xml.

Upvotes: 3

petr k.
petr k.

Reputation: 8110

You can't. One workaround might be to generate a derived class at runtime and adding the attribute, although this is probably bit of an overkill.

Upvotes: 13

Thomas Danecker
Thomas Danecker

Reputation: 4685

No, it's not.

Attributes are meta-data and stored in binary-form in the compiled assembly (that's also why you can only use simple types in them).

Upvotes: 4

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

I don't believe so. Even if I'm wrong, the best you can hope for is adding them to an entire Type, never an instance of a Type.

Upvotes: 3

Related Questions