Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Attributes: One Attribute to Rule Them All?

Is it possible to assign an attribute on a property and use it in order to assign other attributes - doing so without using reflection?

The code:

public class CashierOut : BaseActivity
{
    [Description("Flag indicates whether break to execution.")]
    [DefaultValue(false)]
    [MyCustomAttribute(ParameterGroups.Extended)]
    public bool CancelExecution { get; set; }

    [Description("Flag indicates whether allow exit before declation.")]
    [DefaultValue(true)]
    [MyCustomAttribute(ParameterGroups.Extended)]
    [DisplayName("Exit before declaration?")]
    public bool AllowExitBeforeDeclare { get; set; }
}

I would like to do something like this:

public class CashierOut : BaseActivity
{
    [MyResourceCustom("CashierOut.CancelExecution")]
    public bool CancelExecution { get; set; }

    [MyResourceCustom("CashierOut.AllowExitBeforeDeclare")]
    public bool AllowExitBeforeDeclare { get; set; }
}

public sealed class MyResourceCustom : Attribute
{
    public string ResourcePath { get; private set; }

    public ParameterGroupAttribute(string resourcePath)
    {
        ResourcePath = resourcePath;

        // Get attributes attributes value from external resource using the path.
    }
}
like image 648
Roi Shabtai Avatar asked Jan 24 '12 10:01

Roi Shabtai


2 Answers

Attributes simply add meta data to the members they are defined on - by themselves they do nothing.

You will have to use reflection in order to produce some behaviour depending on the attribute values.

This is how all attributes work - some of the tooling is aware of some attributes (like the compiler and the ConditionalAttribute), but this is still done via reflection.

like image 135
Oded Avatar answered Sep 30 '22 01:09

Oded


Look into Aspect Oriented Programming. You can use tools like postsharp to modify your code either at compile or runtime.

like image 30
Huusom Avatar answered Sep 30 '22 00:09

Huusom