Static Methods and Fields
Define members that belong to the type itself.
Static vs Instance
An instance member belongs to each object; a static member belongs to the class itself. There is exactly one copy of a static member, shared by everyone.
using System;
class Counter
{
public static int Total; // shared
public int Id; // per instance
}
class Program
{
static void Main()
{
Counter.Total = 5;
Console.WriteLine("Shared Total: " + Counter.Total);
}
}Declaring Static Fields
A static field is accessed through the class name, not an instance: ClassName.Field.
using System;
class Bank
{
public static decimal InterestRate = 0.05m;
}
class Program
{
static void Main()
{
Console.WriteLine("Rate: " + Bank.InterestRate);
}
}All lessons in this course
- Static Methods and Fields
- Static Classes for Utilities
- Constants and readonly Fields
- Static vs Instance Design