Search code examples
c#inheritancestatic

Why is overriding static method alowed in C#


protected static new void WhyIsThisValidCode()
{
}

Why are you allowed to override static methods? Nothing but bugs can come from it, it doensn't work as you would think.

Take the following classes.

class BaseLogger
{
    protected static string LogName { get { return null; } }

    public static void Log(string message) { Logger.Log(message, LogName); }
}

class SpecificLogger : BaseLogger
{
    protected static string LogName { get { return "Specific"; } }
}

this is alowed, and the code

SpecificLogger.Log("test");

is altso alowed, but it doesn't do what you would think by looking at the code.

it calls Logger.Log with LogName = null.

So why is this allowed?


Solution

  • The new keyword does not override a method. It instead creates a new method of the same name which is independent of the original. It is not possible to override a static method because they are not virtual