1. Technology

Static Methods in C#

By

In the previous tutorial, we looked at an object functions aka methods and in this one we'll carry on and look at static methods.

In OOP, a class defines a type and instances of that class are created at runtime and are known as objects. The methods declared for those classes usually access or modify member data in the objects.

However it's possible to declare members, including fields and methods to be static. That means it doesn't apply to an instance of the class but to the class itself. There doesn't even have to be any instances of the class created to use static methods and fields.

It's easier to explain with an example.

using System;

namespace csex
{
    class Example
    {
        private int Id;
        private int instance;
        private static int NextInstanceNumber;


        public Example(int id)
        {
            instance = NextInstanceNumber++;
            Id = id;
        }

        static Example()
        {
            NextInstanceNumber = 0;
        }

        public override string ToString()
        {
            return String.Format("Instance # = {0} Next Instance # = {1} Id= {2}",instance, NextInstanceNumber, Id) ;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var ex1 = new Example(234) ;
            var ex2 = new Example(47) ;
            Console.WriteLine(ex1) ;
            Console.WriteLine(ex2) ;
            Console.ReadKey() ;
        }
    }

}

Here we have a class Example that has two instance members and one static field NextinstanceNumber. To make a method or field static add the word static after the access modifier and before the type. So here is a field declared as an instance and a static one:

private int fred; // Instance
private static int count; // static

The example has two constructors, the first one (below) to create instances:

public Example(int id)

and the second one a static constructor.

static Example()

What is a Static Constructor?

It's similar to a normal constructor but is only used to initialize static members. it's also a good place to put code that is only ever run once. However, there are restrictions when using static constructors.

  • No public or private etc access modifiers are allowed and no parameters.
  • It can't be called directly.
  • It gets called sometime before any static variable is accessed and before the first instance of the class is created.

That last point is quite important. The exact point when it is called is not known and if there are any dependencies then that can cause bugs.

So before the first line of Main is reached, the static Example() is called and NextInstanceNumber is set to 0. Because this is a static and not instance member, there is only ever one NextInstanceNumber.

There are two instances of the Example class created; ex1 and ex2 and in each one the current value of NextInstanceNumber is assigned to instance, so ex1.instance gets the value 0, and ex2.instance gets 1. After those are created the value of NextInstanceNumber is 2.

If it helps you can prefix static members with the class name, so this is valid:

instance = Example.NextInstanceNumber++;

Output

Running the example outputs:

Instance # = 0 Next Instance # = 2 Id= 234
Instance # = 1 Next Instance # = 2 Id= 47

In my mind I have a mental image that the objects ex1 and ex2 each have two parts: the instance members including fields and methods if there are any, plus the static members.

Instance methods can access static methods and fields, as the overridden ToString() method shows. But static methods can only access static data. You could add a static method like this:

public static string ToString_static()
{
  return String.Format("Next Instance # = {0}", NextInstanceNumber);
}

And change Main to this:

static void Main(string[] args)
{
  Console.WriteLine(Example.ToString_static());
  Console.ReadKey();
}

Running that would as you expect will output this because no instances have been created.

Next Instance # = 0

Accessing Static Members Externally

In the example the NexTinstanceNumber is private. But you could make it public, or better still a public property with a get and set like this:

public static int NextInstanceNumber { get; set; }

And in Main you could then access it or change it with code like this:

Example.NextInstanceNumber = 5;

There's nothing to stop you passing in an instance to a static method like this:

public static void ResetNextInstance(Example ex)
{
  NextInstanceNumber = ex.instance;
}

Conclusion. Static fields and methods can be useful but in my experience you can write a lot of software and never use them.

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Static Methods in C#

©2014 About.com. All rights reserved.