I have a couple of classes that are singletons so I tried to create a parent BaseClass with method GetInstance(params) and derived classes, that should implement this method and return instances of theiselfs (so I dont have to cast them)... as they are singletons the method should be static, but its not allowed to override static methods. What would be the best approach to code it? sample code what i wanted:
public class Base {
public static virtual T GetInstance<T>() where T : class;
}
public class Derived {
Derived instance;
public static override T GetInstance<T>() where T : typeOf(this){
if (instance == null) {
instance = new Derived();
}
return instance;
}
}
in the code outside of this i want to call
Derived.GetInstance().SomeDerivedMethod()
not
(Derived.GetInstance() as Derived).SomeDerivedMethod() and not
new Derived().getInstance().SomeDerivedMethod()
I know this is not good, and i have lack of experience with the T type too, so any advices are welcomed. thanks
EDIT:
Or if it is possible somehow define the GetInstance() method in Base, so the derived class does not need to ovwerride it, but it will return the instance of class from where it was called... Derived.GetInstance() will return instance of Derived