Can I have 'virtual static function'

  • Thread starter Thread starter babylon
  • Start date Start date
B

babylon

I would like to have a parent class that make one of the static function as
abstract (i can't do it in csharp now)
so that all the subclasses have to implement a static function with same
signature...

is there any way to do it?
e.g.
abstract class parent
{
public abstract static CallMe();
}

class child : parent
{
public static CallMe(); // must implement or compile error.
}


thx
 
I would like to have a parent class that make one of the static function
as
abstract (i can't do it in csharp now)
so that all the subclasses have to implement a static function with same
signature...

Static methods do not require an instance in order to be invoked, therefore
you cannot make them virtual as virtual methods require an object instance.

However, whilst you cannot do such a thing. You can achieve similar by using
a static proxy. For example:

public sealed class MyStaticProxy
{
private static IMyInterface instance = null;

private MyStaticProxy()
{
}

public static void SomeFuntion()
{
}
}
 
I stupidly pressed send by accident, sorry. I'll try and continue (and
pretend I haven't lost any dignity) :)

public sealed class MyStaticProxy
{
private static IMyInterface instance = null;

private MyStaticProxy()
{
}

private IMyInterface Instance
{
get
{
if ( null == instance )
instance = new MyImplementation();

return instance;
}
}

public static void SomeFuntion()
{
Instance.SomeFuntion();
}
}

This provides something akin to a singleton, the instantiation of the
MyImplementation object could easily be a call to a class factory allowing
you to change the actual implementation during initialisation, however the
static methods allow a central access point to the rest of the application.

n!
 
Back
Top