It makes no sense to me why C# doesn't support static methods & static properties in interfaces. In a brief survey of other SO questions on the issue, I come across a variety of answers ranging from "it's apparently an oversight in the design of C# and/or the CLR, and fixing it would break existing code" all the way to "interfaces are meant to interact with objects, and if you find yourself wanting to use interfaces otherwise, you're obviously lacking grey matter and should probably go back to sweeping floors". This question exhibits the full range of such answers.
I need a family of parsers, each with a method that determines if the assembly file contents passed to it matches its platform type. These are stateless entities; there's no reason to have "objects" of these parsers other than that C# interfaces require class instances. If I rip out all the "static
" keywords below, this code compiles without error.
public interface IParser
{
static string platformName { get; }
static bool isThisPlatform(string asmFileContents);
static bool parseAsm(string asmFileContents);
}
class PIC32MX_GCC_Parser : IParser
{
public static string platformName { get { return "PIC32MX_GCC"; } }
public static bool isThisPlatform(string asmFileContents)
{
return false; // stub
}
public static bool parseAsm(string asmFileContents)
{
return false; // stub
}
}
class M16C_IAR_Parser : IParser
{
public static string platformName { get { return "M16C_IAR"; } }
public static bool isThisPlatform(string asmFileContents)
{
return false; // stub
}
public static bool parseAsm(string asmFileContents)
{
return false; // stub
}
}
IParser[] parsers =
{
new PIC32MX_GCC_Parser(),
new M16C_IAR_Parser()
};
public IParser findTheRightParser(string asmFileContents)
{
foreach(IParser parser in parsers)
{
if (parser.isThisPlatform(asmFileContents))
{
Console.WriteLine("Using parser: ", parser.platformName);
return parser;
}
}
return null;
}
I'd like to ask why C# won't let me do this, but I know the answer is just "because it doesn't." I know the "workaround" is to just implement them as instance methods which, if necessary, call a static method (which isn't actually necessary in this case).
Since there are a number of people out there (many with high SO rep) who think that putting static methods in interfaces makes no logical sense and if you want to do so there's something wrong with your design, or your head (or both), I'd like some of those people to help me out & give me a good, simple alternative to my code above which uses static methods and doesn't simply "work around" the issue by having instance methods wrap static methods.