Get member to which attribute was applied from inside attribute constructor?

Related searches

I have a custom attribute, inside the constructor of my custom attribute I want to set the value of a property of my attribute to the type of the property my attribute was applied to, is there someway to access the member that the attribute was applied to from inside my attribute class?

Attributes don't work that way, I'm afraid. They are merely "markers", attached to objects, but unable to interact with them.

Attributes themselves should usually be devoid of behaviour, simply containing meta-data for the type they are attached to. Any behaviour associated with an attribute should be provided by another class which looks for the presence of the attribute and performs a task.

If you are interested in the type the attribute is applied to, that information will be available at the same time you are reflecting to obtain the attribute.

Writing Custom Attributes, Class, indicating that your attribute can be applied only to a class, or AttributeTargets. This public constructor takes a parameter and sets a member This is a read-only attribute. public virtual string Name { get {return name� Retrieves a custom attribute applied to a module. Parameters specify the module, and the type of the custom attribute to search for. GetCustomAttribute (MemberInfo, Type) Retrieves a custom attribute applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.

It's possible from .NET 4.5 using CallerMemberName:

[SomethingCustom]
public string MyProperty { get; set; }

Then your attribute:

[AttributeUsage(AttributeTargets.Property)]
public class SomethingCustomAttribute : Attribute
{
    public StartupArgumentAttribute([CallerMemberName] string propName = null)
    {
        // propName = "MyProperty"
    }
}

CustomAttributeData.Constructor Property (System.Reflection , For example, attributes could be used to indicate whether a class is into the constructor), and exposes this as a property which can be queried at runtime. We need get details of each member in the class, and then iterate through the� Examples. The following example defines a custom attribute with four constructors and four properties. Two of the properties are read-only, and are set by using the positional parameters of the constructors.

You can do next. It is simple example.

//target class
public class SomeClass{

    [CustomRequired(ErrorMessage = "{0} is required", ProperytName = "DisplayName")]
    public string Link { get; set; }

    public string DisplayName { get; set; }
}
    //custom attribute
    public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
{
    public string ProperytName { get; set; }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var propertyValue = "Value";
        var parentMetaData = ModelMetadataProviders.Current
             .GetMetadataForProperties(context.Controller.ViewData.Model, context.Controller.ViewData.Model.GetType());
        var property = parentMetaData.FirstOrDefault(p => p.PropertyName == ProperytName);
        if (property != null)
            propertyValue = property.Model.ToString();

        yield return new ModelClientValidationRule
        {
            ErrorMessage = string.Format(ErrorMessage, propertyValue),
            ValidationType = "required"
        };
    }
}

Using Custom Attributes in C#, Attributes are used to impose conditions or to increase the efficiency of a Constructor overloading can be used to handle different assignments while Attributes can have properties like get and set for its members as well. The attribute is constructed only when you retrieve it (using the GetCustomAttribute function). Otherwise, its construction recipe (constructor overload + positional parameters + properties values) is only stored in the assembly metadata. In your case, I'd retieve all enum types from the assembly, and check if they have the attribute.

Custom Attributes in C#, Because these attribute values become just another part of the metadata bound That member property can only ever be used through an instance or subclass The first method in our Attribute class is the class constructor, which has a call� §24.1.3 Attribute parameter types. The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are: One of the following types: bool, byte, char, double, float, int, long, short, string. The type object. The type System.Type.

Defining and Using Custom Attribute Classes in C#, Attributes are a .NET programming construct that enables an object known as an attribute to be associated with a type or other program element. The program element to which an attribute is applied is known as the attribute target. The attribute usually contains metadata about its target.

Constructor overloading can be used to handle different assignments while provoking Attribute class objects. public MyAttribute(dataType value) { this.value = value; } Note: Custom Attributes can have properties like get and set for its members as well.

Comments
  • Can you briefly describe the use-case?
  • If you can provide more detail to the problem you are solving, it might be possible to provide an alternative solution.
  • Thanks, I know how I can achieve the same in a different way, but I wanted to know if this was possible because the code would be cleaner.
  • As you say, it's not the end of the world as you know the type when getting the custom attribute via Reflection but it would be "nice" if the Type passed in to GetCustomAttribute was also stored in the System.Attribute
  • This should be the marked answer now! Exactly what I needed, thank you!
  • This was added some time ago, but I have a follow up question: According to this link [docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… [CallerMemberName] only gives you the member name, not in a fully qualified way. So if I want to get that type via reflection, how can I know it's full name?