user366312
user366312

Reputation: 16904

Is there any way to make a static method mandatory to be implemented in the implemented/derived class?

Since, an interface doesn't encompass a static method, is there any way to make a static method mandatory to be implemented in the implemented/derived class?

If not, is there any other way to achieve this objective?

I am actually making all my database classes look like this:

class MyClass : IMyClass, IPersistant
{
public int ID {get;set}
.....
.....
public int SaveOrUpdate(){}//returns the ID
public static MyClass Get(int id){}
public static IEnumerable<MyClass> Get(){}
public bool Delete(){}
}

Upvotes: 0

Views: 204

Answers (3)

Alexander Torstling
Alexander Torstling

Reputation: 18898

If I guess what you are trying to do correctly, you could have a separate type of class for loading persistent objects and let it implement the Get functions (something like MyClass c = new MyClassLoader(database).Get(25)).

I'm saying this since you seem to have gotten stuck at the fact that the Get functions must exist before there are any instances, and therefore concluded that they need to be static. By separating the loading code into another type you can avoid this.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500275

No, there isn't. Static methods aren't polymorphic.

There's currently no good way of doing this, really. You can have parallel type hierarchies - one for instances and one sort of "meta" hierarchy with instance methods where you'd otherwise have static ones, but that gets pretty ugly too.

If you could say more about what you're trying to do, we may be able to come up with alternative suggestions.

EDIT: It looks like you really want a Repository<T> parallel hierarchy for fetching individual items or collections.

Upvotes: 6

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

If you want virtual constructors, use an abstract factory class.

Otherwise, you'll need to me more specific about what you wish to accomplish.

Upvotes: 0

Related Questions