I know this question has been asked over and over, but I can’t seem to find good enough answers. So to make it clear what I’m trying to know, I’ll split this in two questions:
-
Why can’t interfaces have static method signatures? I’ll try to preempt the non-answers asking why in the world I would want to do this with the following: I would want to be able to statically invoke
GetDbConnectionType()onSqliteCodeGeneratorandMssqlCodeGenerator:interface ICodeGenerator { // this is the method I would like to be static: string GetDbConnectionType(); } abstract class CodeGeneratorBase : ICodeGenerator { public abstract string GetDbConnectionType(); public void GenerateSomeCode(StringBuilder s) { s.AppendLine("var foo = new " + GetDbConnectionType() + "();"); } } class SqliteCodeGenerator : CodeGeneratorBase { public override string GetDbConnectionType() { return "SQLiteConnection"; } } class MssqlCodeGenerator : CodeGeneratorBase { public override string GetDbConnectionType() { return "SqlConnection"; } } -
On the other hand, and this is the matter of this second question, if you know of a good alternative to reach the aforementioned goal, then by all means…
Suppose you could specify in an interface that a type had to have a particular static method… how would you call it? Polymorphism works through instances – whereas static members explicitly don’t use instances.
Now, having said that, there’s one situation in which I can see static interface members working: generic types. For example:
That would call the static member on the concrete type
T.I’ve blogged more about this, but I suspect the benefit doesn’t justify the complexity.
In terms of alternatives – usually you’d have another interface, and have separate types to implement that interface. That works well in some contexts, but not in others.