Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is restricting attributes to class or properties doable?

I have two custom attributes defined like so:

internal class SchemaAttribute : Attribute {
    internal SchemaAttribute(string schema) {
        Schema = schema;
    }

    internal string Schema { get; private set; }
}

internal class AttributeAttribute : Attribute {
    internal AttributeAttribute(string attribute) {
        Attribute = attribute;
    }

    internal string Attribute { get; private set; }
}

I would like to restrict the SchemaAttribute to classes, and the AttributeAttribute to properties.

Is this doable?

like image 244
Will Marcouiller Avatar asked May 21 '10 18:05

Will Marcouiller


People also ask

Why we need attributes in C#?

Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection.

What are attributes of class in C#?

In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.


2 Answers

Check out AttributeUsage and AttributeTargets.

It'll look something like:

[AttributeUsage(AttributeTargets.Class)]
internal class SchemaAttribute : Attribute
{
    // Implementation
}

[AttributeUsage(AttributeTargets.Property)]
internal class AttributeAttribute : Attribute
{
    // Implementation
}
like image 64
Justin Niessner Avatar answered Oct 26 '22 04:10

Justin Niessner


Look at AttributeTargetAttribute

[AttributeTarget(AttributeTargets.Class)]
internal class SchemaAttribute : Attribute
...

[AttributeTarget(AttributeTargets.Property)]
internal class AttributeAttribute: Attribute
...
like image 38
Phil Lamb Avatar answered Oct 26 '22 04:10

Phil Lamb