O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required