Hasan Hasan - 13 days ago 6
C# Question

Restrict child attributes for multiple usage

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public abstract class AttBase : Attribute
{
public static string Apply(object obj);
}
public class FooAttribute : AttBase {}
public class BarAttribute : AttBase {}

public class MyClass
{
[Foo]
[Bar]
public string MyProperty { get; set; }
}


I want to restrict developer to use only one of each derivered attribute at a time. Compiler should give compile error at this stage. How can I achieve this? Is it possible?

Answer

The AllowMultiple = false seems to influence only on the same attribute type and not derived\sibling attributes classes

If your purpose is to add some unique indicator to the class for some usage, simply define some enum instead of derived classes and add it as property for the AttBase

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class AttBase : Attribute 
{
   public IndicatorType Indicator {get;set;}
   public AttBase(IndicatorType indicator )
   {
      Indicator = indicator;
   }
}

public enum IndicatorType 
{
  Foo,
  Bar,
}

public class MyClass
{
    [AttBase(IndicatorType.Foo)]
    public string MyProperty { get; set; }
}

If your intention was to take the Foo or Bar class and activate it on the string , use System.Type instead of the enum

Comments