From Java to C#: A Developers Guide

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 a reference to an instance of that class. You need to use the class name to invoke a static method, or access a static member. Java allows you to invoke a static method using a variable referring to an instance of the class, as shown in the example below.

You can do this in Java:

1: // TestMain.java 2: public class TestMain{ 3: public static void main(String args[]){ 4: TestClass c = new TestClass(); 5: c.doSomething(); // or TestClass.doSomething(); 6: } 7: } 8: class TestClass{ 9: public static void doSomething(){ 10: System.out.println("running static method"); 11: } 12: }

However in C#, this will give a compilation error:

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

Compilation error:

Test.cs(4,5): error CS0176: Static member 'TestClass.DoSomething()' cannot be accessed with an instance reference; qualify it with a type name instead

Additional notes

  • The static keyword can be used with fields, methods, properties, operators, and constructors, but cannot be used with indexers, destructors, or types.

  • Static function members (methods, instance constructors, properties, and operators) are always non-virtual.

  • A static member cannot be declared with the following modifiers: virtual , override, and abstract .

Категории