Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 524
tpower Avatar asked Feb 23 '09 14:02

tpower


2 Answers

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.

like image 115
Marc Gravell Avatar answered Sep 22 '22 15:09

Marc Gravell


No. Basically it sounds like you're after a sort of "static polymorphism". That doesn't exist in C#, although I've suggested a sort of "static interface" notion which could be useful in terms of generics.

One thing you could do is write a simple unit test to verify that all of the types in a particular assembly obey your rules. If other developers will also be implementing the interface, you could put that test code into some common place so that everyone implementing the interface can easily test their own assemblies.

like image 25
Jon Skeet Avatar answered Sep 18 '22 15:09

Jon Skeet