7.12. Static methods

Static methods in C# are very similar to static methods in Java. You declare a static method using the static keyword. A static method belongs to the class as a whole, rather than to a single instance of the class.

Similiarly, you invoke a static method by prefixing the method name with the class name followed by a dot.

 1: using System;
 2:
 3: class MainClass{
 4:   static void Main(){
 5:     TestClass.DoSomething();
 6:   }
 7: }
 8:
 9: class TestClass{
10:   static public void DoSomething (){
11:     Console.WriteLine("running static method");
12:   }
13: }

Output:

c:\expt>test
running static method

Like Java

A static method cannot refer to non-static methods or other non-static members.

Unlike Java

You cannot invoke a static method using ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.