C# Static Methods


This entry is part 5 of 8 in the series C# Classes Intermediate

In a previous post we discussed static fields. The first thing to note is that static methods of a class can be called even if there are no instances of the class. Our Main method just goes ahead and calls the class X.

Static function members, like static fields, are independent of any class instance. Even if there are no instances of a class, you can still call a static method. Static function members cannot access instance members. They can, however, access other static members. For example, the following class contains a static field and a static method. Notice that the body of the static method accesses the static field.

If you declare a class as static, all of its members must be static and you must use the static keyword for all of the members. If you omit the static keyword on any of the members you get an error message saying “cannot declare instance members in a static class”.

using System;
namespace StaticMethodsIllustrated
{
    static class X
    {
        static public int A; // Static field
        static public void PrintValA() // Static method
        {
            Console.WriteLine("Value of A: {0}", A);
            Console.WriteLine($"Value of A: {A}");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {   // no instantiation here
            X.A = 10; // Use dot-syntax notation
            X.PrintValA(); // Use dot-syntax notation
        }
    }
}

Series Navigation<< C# Static FieldsC# Constants >>