C# Static Method

Static

Static methods have no instances. They are called with the type name, not an instance identifier. They are slightly faster than instance methods because of this. Static methods can be public or private.

Static

Example

This program defines both static methods and regular instance methods. The static methods use the static keyword somewhere in the method declaration signature, usually as the first keyword or the second keyword after public.

KeywordsMethod call

Static:A static method cannot access non-static class level members. It has no "this" pointer.

Instance:An instance method can access those members, but must be called through an instantiated object. This adds indirection.

Program that uses instance and static methods: C#

using System;

class Program
{
    static void MethodA()
    {
	Console.WriteLine("Static method");
    }

    void MethodB()
    {
	Console.WriteLine("Instance method");
    }

    static char MethodC()
    {
	Console.WriteLine("Static method");
	return 'C';
    }

    char MethodD()
    {
	Console.WriteLine("Instance method");
	return 'D';
    }

    static void Main()
    {
	//
	// Call the two static methods on the Program type.
	//
	Program.MethodA();
	Console.WriteLine(Program.MethodC());
	//
	// Create a new Program instance and call the two instance methods.
	//
	Program programInstance = new Program();
	programInstance.MethodB();
	Console.WriteLine(programInstance.MethodD());
    }
}

Output

Static method
Static method
C
Instance method
Instance method
D
ABC: letters

This program defines five methods, MethodA, MethodB, MethodC, MethodD and Main. The execution engine first encounters and compiles the Main method. The MethodA static method is invoked and its internal logic is executed.

Then:The Program.MethodC parameterless method is invoked and it internally prints a message.

Static

Also:It returns a value, which is placed on the evaluation stack and printed with Console.WriteLine.

Console.WriteLine

Next, the program uses the two instance methods, MethodB and MethodD. Because these two methods are instance methods not decorated with the static keyword, you must create a new object instance to call them.

Note:They are part of the Program class definition.
So we create a new Program instance.
We use the dot notation to invoke them.

Class

Public, private

Star, asterisk character

Many static methods you develop will need to be declared in the public accessibility domain. Utility classes often contain public static methods, and this results in no performance loss and a method that is available to every caller.

You can also use the internal keyword to describe a method that must only be called in the same assembly as the method implementation. Private static methods are also useful as internal logic repositories for the class state.

Public MethodPrivate Method

Local variables

Const keyword

Static locals are a kind of storage-permanent local variable in the C and C++ languages. This concept does not exist in the C# language and when translating programs you must use a type-level static variable and reference it instead.

The static keyword is not valid in the method body. The const keyword however can be used to create a method-local constant definition. Const local variables are widely used and help document your code.

Const

Classes

Note

Static classes are a way to specify that a type must not be created as an instance. So a static class and a regular class are the same in every way except the language prevents you from creating a new instance of the static class.

So:This could reduce programming errors but has no other runtime effects. Static constructors do have an effect on the type's behavior.

Static Constructor

Performance

Performance optimization

Static methods are normally faster to invoke on the call stack than instance methods. There are several reasons for this in the C# language. Some have to do with the intermediate language implementation.

Instance methods actually use the 'this' instance pointer as the first parameter. They will always have that overhead. Instance methods are also implemented with the callvirt instruction, which imposes a slight overhead.

callvirt Instruction

Note:Changing your methods to static methods is unlikely to help much on ambitious performance goals, but it can help.

Properties

Property

Properties are essentially a special type of method and are actually implemented the same way in the metadata format. In the metadata, properties have the word "get_" or "set_" prefixed to their identifiers.

Tip:You can use static properties in the same way as static methods. Properties show the same performance levels of methods.

Property

Access routines

Code Complete

There are many ways you can use access routines and global variables. The book Code Complete by Steve McConnell outlines strategies to employ global variables in programs without creating maintainability problems over time.

Note:Mainly, the author emphasizes the usage of access routines. In the C# language, you can use static properties as access routines.

Code Complete: Book ReviewGlobal Variable

Fields

Class: shapes

Let's describe the usage of fields in static and instance methods. Static methods have no way of accessing fields that are instance fields, as instance fields only exist on instances of the type.

Instance methods can however access static fields with no problem. This means that using the static keyword restricts the available members of the type. You can sometimes fix compilation bugs by removing the static keyword.

Static FieldCompile-Time Error

Summary

Static methods in the C# language differ from instance methods in both the method declarations and in the method call sites. Static methods apply to a type, not an instance of the type they are defined on.


C#: Method