C# Static Methods

Summary: in this tutorial, you’ll learn about the C# static methods and how to use them effectively.

Introduction to the C# static methods

To define a method static, you use the static keyword with the following syntax:

class MyClass
{
    public static type MyStaticMethod(parameters)
    {
        // 
    }
}Code language: PHP (php)

In this syntax, the static keyword denotes that the MyStaticMethod is a static method.

Like static fields, static methods are bound to a class. They are not bound to any instances of the class. Therefore, static methods cannot access instance members. However, they can access other static members.

To call a static method inside the class, you use the static method name:

MyStaticMethod(arguments);Code language: JavaScript (javascript)

To call a static method outside the class, you use this syntax:

ClassName.MyStaticMethod();Code language: CSS (css)

In practice, you use define static methods in a utility class.

C# static method examples

Let’s take the example of using the static method.

First, define the UnitConverter class that has two static methods:

class UnitConverter
{
    public static double KgToLbs(double weight) => weight * 2.20462262185;

    public static double LbsToKg(double weight) => weight * 0.45359237;

}Code language: PHP (php)

The KgToLbs converts weight from kilogram to pound and the LbsToKg method converts the weight from pound to kilogram.

Second, call the KgToLbs() static method to convert weight from kilogram to pound:

// Program.cs

// kg -> pound
double weight = UnitConverter.KgToLbs(100);
Console.WriteLine($"100kg={weight:#.00}lbs");

// pound -> kg
weight = UnitConverter.LbsToKg(100);
Console.WriteLine($"100lbs={weight:#.00}kg");Code language: JavaScript (javascript)

Output:

100kg = 220.46lbs
100lbs = 45.36kg

Summary

  • Static methods are bound to classes, not instances of classes.
  • Group related static methods in a utility class.
Was this tutorial helpful ?