-2

I wanted to elaborate on the current project i'm working on but that would be kind long. Instead I'll just post a programming riddle which basically explains what i'm trying to accomplish. :)

abstract class A
{
    // key = Derived Class name, value = list of properties the derive class exposes.
    private static Dictionary<string, List<string>> _DerivedPropertyNames;

    static A()
    {
        InitializeDerivedPropertyNames();
    }

    private static void InitializeDerivedPropertyNames()
    {
        //...???...
    }
}

The riddle is how can you create an abstract base class which will hold a static cache of all its derived classes properties?

Note that the idea is to avoid loading an assembly by name.

JarJarrr
  • 400
  • 3
  • 18
  • 2
    Do you want to enumerate only the derived classes that exist in the currently executing assembly? – Frédéric Hamidi May 15 '11 at 08:58
  • hmmmm thats i good question...well since in our project this is framework code then i suppose the answer is no. – JarJarrr May 15 '11 at 09:01
  • 2
    >abstract base class which will hold a static cache of all its derived classes properties . Can you explain WHY? This doesnt look like something, that is actualy usable. – Euphoric May 15 '11 at 09:04
  • if `A` is public and not internal (i.e. is visible outside of its own assembly), what you want to achieve doesn't seem to be doable. For instance, I could derive a class from `A` in my own assembly, and code in `A` wouldn't even now that assembly exists. Of course, even if it knew, it still would have to load it in order to access its types. – Frédéric Hamidi May 15 '11 at 09:28
  • the idea behind this is to have the base class hold values of attributes the derive classes put on their properties – JarJarrr May 15 '11 at 10:33

2 Answers2

1

There is no easy (efficient) way to do this in the base class.
Simply implement a static constructor in every derived class and use it to register the properties.

Also take a look at Dependency properties in the WPF Fx, for comparison.

H H
  • 263,252
  • 30
  • 330
  • 514
0

If you can wait for instances of the child types to be instantiated, then you could use A's regular constructor to register the implementing class:

public A()
{
    Type childType = GetType();
    string className = childType.Name;
    if (!_DerivedPropertyNames.ContainsKey(className)) {
         // add properties for this class
    }
}

It will be very difficult for you to get the job done in the static constructor, before any instantiation, without adding logic in the child classes (which I suppose you don't want). The reason is that you won't be able to enforce all assemblies containing types that implement A to be loaded when A's static constructor is called.

tugudum
  • 387
  • 1
  • 4