6

Possible Duplicate:
How can I force inheriting classes to implement a static method in C#?

I understand abstract and static are opposite, but I want to force derived classes to implement a static method. how can I do that?

Edit after SimonC : While trying to describe what I want to do, i realized that static methods of super class will not be able to call the overridden subclass version.

But olivier's alternative solution looks nice.

Community
  • 1
  • 1
bokan
  • 3,601
  • 2
  • 23
  • 38
  • 2
    In short, you can't. Why do you want to do this? – SimonC Nov 26 '12 at 14:38
  • A use case here would be to have a static "CreateDefault" method that returns an object of the parent class, but each child class overrides it. Now I get it that it doesn't really make sense because in order to use it you still need to call CreateDefault using the static context of the child which defeats the purpose of using inheritance. It seems to me that the real advantage being sought here is a compiler time check that the sub classes implement a static method. – C. Tewalt May 11 '16 at 13:11
  • Again, this doesn't really help much because it doesn't enforce that your static method is used anywhere. I think the singleton idea from Olivier's answer is really the best. I agree with @SimonC 's sentiment that a dev should take a step back and figure out what they're really trying to accomplish by attempting to have a static method in the parent and overridden in child classes. – C. Tewalt May 11 '16 at 13:15

3 Answers3

15

A possible approach of combining a static behavior with inheritance or interface implementation is to use the singleton pattern. The access to a singleton object is static, but the object is created with new like a "normal" object

public interface ISomeInterface { ... }

public class SomeClass : ISomeInterface
{ 
    public static readonly SomeClass Instance = new SomeClass();

    private SomeClass()
    { 
    }

    // TODO: Implement ISomeInterface
    // and/or override members from a base class.
}

Accessing a method of the singleton

ISomeInterface obj = SomeClass.Instance; // Static access to interface.
var y = obj.SomeMethod(x);
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
5

You cannot. Static methods are not subject to polymorphic behavior. You cannot even override static methods voluntarily, let alone force a class to override them.

Tudor
  • 61,523
  • 12
  • 102
  • 142
3

Sorry, but it is impossible. Abstract and/or base classes are all about the object inheritance.

static methods are specific to one and only one class and are NOT inheritable.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
  • 1
    this is not true in general OOP. seems more related to c# only. if i have a helper function striping some string value in the parent, and all child classes uses the same function, why cant i just keep it static in the parent class? – ulkas Mar 12 '19 at 11:04