Is there a way to force a C# class to implement certain static functions?

tpower picture tpower · Feb 23, 2009 · Viewed 19.7k times · Source

I am developing a set of classes that implement a common interface. A consumer of my library shall expect each of these classes to implement a certain set of static functions. Is there anyway that I can decorate these class so that the compiler will catch the case where one of the functions is not implemented.

I know it will eventually be caught when building the consuming code. And I also know how to get around this problem using a kind of factory class.

Just curious to know if there is any syntax/attributes out there for requiring static functions on a class.

Ed Removed the word 'interface' to avoid confusion.

Answer

Marc Gravell picture Marc Gravell · Feb 23, 2009

No, there is no language support for this in C#. There are two workarounds that I can think of immediately:

  • use reflection at runtime; crossed fingers and hope...
  • use a singleton / default-instance / similar to implement an interface that declares the methods

(update)

Actually, as long as you have unit-testing, the first option isn't actually as bad as you might think if (like me) you come from a strict "static typing" background. The fact is; it works fine in dynamic languages. And indeed, this is exactly how my generic operators code works - it hopes you have the static operators. At runtime, if you don't, it will laugh at you in a suitably mocking tone... but it can't check at compile-time.