views:

79

answers:

1

As it is not possible to override a static class in c#, if i want to override a method I generally define a delegate matching the signature of the static method, then modify the method along the lines of:

public static void foo(int bar)
{
  if (delegatename!=null)
  {
   delegatename.Invoke(bar);
  }
  else
  {
   //execute previous code as normal
  }
}

I feel a twinge of guilt, knowing this is a bit messy.

Can anyone suggest a neater solution to this problem (other than rewriting the original structure)

+3  A: 

It seems that you are using the static class as a way to provide a single access point to some resource in your application. If it is the case, you should consider to use an implementation of Singleton design pattern. Doing it, you could take advantage of use inheritance on your non-static classes.

public abstract class Base { ... }

public class Impl : Base { ... }

public class Singleton : Impl
{ 
    #region Static Members

    static readonly Singleton _instance = new Singleton(); 

    static Singleton() { } 

    static public Singleton Instance 
    { 
        get  { return _instance; } 
    } 

    #endregion Static Members

    #region Instance Members

    private Singleton() { } 

    // Method overrides goes here...

    #endregion Instance Members
} 

A deeper discussion on how to implement the singleton design pattern on C# can be found on Implementing the Singleton Pattern in C# article.

Carlos Loth