What is the best way to define a static property which is defined once per sub-class?

Two possible approaches:

  • Use attributes; decorate each subclass with an attribute, e.g.

    [MyProperty(5)]
    public class DerivedAlpha
    {
    }
    
    [MyProperty(10)]
    public class DerivedBeta
    {
    }
    

    That only works when they're effectively constants, of course.

  • Use a dictionary:

    var properties = new Dictionary<Type, int>
    {
        { typeof(DerivedAlpha), 5) },
        { typeof(DerivedBeta), 10) },
    };
    

EDIT: Now that we have more context, Ben's answer is a really good one, using the way that generics work in C#. It's like the dictionary example, but with laziness, thread-safety and simple global access all built in.


Jon has a good solution as usual, although I don't see what good attributes do here, since they have to be explicitly added to every subtype and they don't act like properties.

The Dictionary approach can definitely work. Here's another way to do that, which explicitly declares that there will be one variable per subclass of BaseEntity:

class FilteredProperties<T> where T : BaseEntity
{
     static public List<string> Values { get; private set; }
     // or static public readonly List<string> Values = new List<string>();
     static FilteredProperties()
     {
         // logic to populate the list goes here
     }
}

The drawback of this is that it's rather difficult to pair with a GetType() call such as you might use in methods of BaseEntity. A Dictionary, or wrapper thereto which implements lazy population, is better for that usage.