views:

77

answers:

5

Hi,

I have one abstract class -let's say myBase. And I want all the classes derived from myBase to have one static field called

public static List<string> MyPArameterNames 
{
get {return _myParameterNames;} 
}

So, every child class can tell what parameter names it uses; I want static because I do not want to create an instance just for this.

How can I achieve this?

+3  A: 

You can't do that. Interfaces, abstract, etc. cannot not apply to static members. If you want to accomplish this, you will have to manually remember to do it on all deriving classes.

Also, static members are inherited by deriving classes. Child classes must hide the static parent member if they wish to specify alternate behavior.

Zach Johnson
A: 

It is imposible. Inheritance cannot be aplied to the members of the type (static members).

Andrew Bezzub
A: 

You can, in the constructor for MyBase, call GetType() and use reflection to ensure the derived class has the correct property. Obviously, that's only going to pick it up at runtime, but I'm not really sure what the point of this constraint would be anyway: what's the harm if the static property isn't there?

Dean Harding
A: 

It doesn't make sense, anyway, as you'd have no way to access that static property without determining the type, thus breaking the whole point of having an interface anyway.

I'd just put a property on the interface, and route it to the static member.

public interface IMyInterface
{
    public void Foo();
    public IList<string> Properties{get;}
}

public class ConcreteClass : IMyInterface
{
    public void Foo(){}
    public IList<string> Properties
    {
        get{ return s_properties; }
    }
}

But that leads me to the second question - what is it that you are trying to accomplish? Why do you need to have a static member on the class? What you really want is, given an object, to be able to determine what properties it has, right? So why would your code care if they're stored statically or per instance? It seems like you're confusing contract (what you want to be able to do) with implementation (how the provider of the service accomplishes the goal).

kyoryu
A: 

Ok. Maybe I was not clear enough. But I have achieved basically what I need by doing something like this:

public abstract myBaseClass
{
 public List<string> MyParameterNames
   {
     get 
         {
             throw 
               new ApplicationException("MyParameterNames in base class 
                                 is not hidden by its child.");
         }
   }
}

So any class derived from this class, will throw an exception if MyParameterNames property is tried to reach the parameter names of that derivedclass.

Not a perfect way, but it helps me to overcome my problem in a way.

burak ozdogan