C# – Force Derived Class to Implement Static Method C#

abstract classcclass-designobject-oriented

So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.

Also, the signature of these CRUD methods are similar.

E.g.
ClassA will have CRUD methods with these type of Signatures

  1. public static List<ClassA> Get()
  2. public static ClassA Get(int ID)
  3. public static bool Insert(ClassA objA)
  4. public static bool Update(int ID)
  5. public static bool Delete(int ID)

ClassB will have CRUD signatures like

  1. public static List<ClassB> Get()
  2. public static ClassB Get(int ID)
  3. public static bool Insert(ClassB objB)
  4. public static bool Update(int ID)
  5. public static bool Delete(int ID)

So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.

For E.g. BaseClass will have CRUD methods like

  1. public virtual static List<BaseClass> Get()
  2. public virtual static BaseClassGet(int ID)
  3. public virtual static bool Insert(BaseClass objBase)
  4. public virtual static bool Update(int ID)
  5. public virtual static bool Delete(int ID)

But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.

So is there any way out?

Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.

Anything that can be done with Abstract class?

Best Answer

Such methods shouldn't be static (what if you have to deal with two databases?) and they also shouldn't be on your entity classes.

Instead, you should have a separate type, that represents the storage for this entity. That type could be generic, so that code that's not entity-specific doesn't have to be repeated.

This way, inheritance works (storage for ClassA can inherit from some base storage) and you don't have to perform the nonsensical "I have to create a person to get a list of all persons".

This pattern is for example used by Entity Framework, there the storage type is called DbSet<T>.