Can a static method be overridden in C#?

aspiring picture aspiring · Feb 12, 2013 · Viewed 59.3k times · Source

I was told that static methods are implicitly final and therefore can't be overridden. Is that true?

  1. Can someone give a better example of overriding a static method?

  2. If static methods are just class methods, what is the real use of having them?

Answer

atlaste picture atlaste · Feb 12, 2013

(1) Static methods cannot be overridden, they can however be hidden using the 'new' keyword. Mostly overriding methods means you reference a base type and want to call a derived method. Since static's are part of the type and aren't subject to vtable lookups that doesn't make sense.

E.g. statics cannot do:

public class Foo { 
    public virtual void Bar() { ... }
}
public class Bar : Foo {
    public override void Bar() { ... }
}

// use:
Foo foo = new Bar(); // make an instance
foo.Bar(); // calls Bar::Bar

Because statics don't work on instances, you always specify Foo.Bar or Bar.Bar explicitly. So overriding has no meaning here (try expressing it in code...).

(2) There are different usages for static methods. For example, it's being used in the Singleton pattern to get a single instance of a type. Another example is 'static void Main', which is the main access point in your program.

Basically you use them whenever you don't want or cannot create an object instance before using it. For example, when the static method creates the object.

[update]

A simple hiding example:

public class StaticTest
{
    public static void Foo() { Console.WriteLine("Foo 1"); }
    public static void Bar() { Console.WriteLine("Bar 1"); }
}

public class StaticTest2 : StaticTest
{
    public new static void Foo() { Console.WriteLine("Foo 2"); }
    public static void Some() { Foo(); Bar(); } // Will print Foo 2, Bar 1
}

public class TestStatic
{
    static void Main(string[] args)
    {
        StaticTest2.Foo();
        StaticTest2.Some();
        StaticTest.Foo();
        Console.ReadLine();
    }
}

Note that if you make the classes static, you cannot do this. Static classes have to derive from object.

The main difference between this and inheritance is that the compiler can determine at compile-time which method to call when using static. If you have instances of objects, you need to do this at runtime (which is called a vtable lookup).