<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Object-oriented programming
All lessons in this course

Lesson 21 of 60 12 minIntermediate

Static members and static classes

Data and methods that belong to the class itself instead of to each object: static fields, methods, classes and constructors.

Everything we put in classes so far belonged to each object: every Beam has its own Length. Sometimes data or behaviour belongs to the class as a whole: the total number of beams created, a conversion factor, a helper that needs no object. That is what static is for.

Interactive

Static: one copy shared by all

Beam.cs
class Beam{    public static int Count;      // ONE copy, shared    public string Mark;           // one copy PER object     public Beam(string mark)    {        Mark = mark;        Count++;                  // same Count for every Beam    }     public static void Reset() => Count = 0;}
The Beam class itself (one, always)
static int Count0
Objects (one per new)
No objects yet, but Count already exists: it belongs to the class.
Count exists once, in the class, even before any Beam is created. Mark is created fresh inside each object.

Instance vs static

Instance memberStatic member
Belongs toeach objectthe class (one copy)
Accessed withobj.MemberClassName.Member
Exists whenafter newas soon as the class is used
Can use thisyesno (there is no current object)
Examplebeam.LengthMath.PI, Console.WriteLine, int.Parse

Static methods

Units.cs
public static class Units{    public const double MmPerInch = 25.4;     public static double InchToMm(double inches) => inches * MmPerInch;    public static double MmToInch(double mm) => mm / MmPerInch;} Console.WriteLine(Units.InchToMm(10));   // no object neededConsole.WriteLine(Units.MmToInch(50.8));
Output
254
2

A static method can only use its parameters and other static members. It can’t read instance fields directly, because it has no object to read them from.

Static classes

A class marked static can contain only static members and can’t be instantiated (new Units() is an error). Use it for groups of related helpers, like Math, Console, File or your own Units.

Static fields: shared state

Ids.cs
public class Member{    private static int _nextId = 1;   // shared by all Members    public int Id { get; }     public Member()    {        Id = _nextId++;               // each new object gets the next number    }} var a = new Member();var b = new Member();Console.WriteLine($"{a.Id}, {b.Id}");
Output
1, 2

const vs static readonly

Constants.cs
public class Config{    public const int MaxLevels = 50;                          // compile-time constant    public static readonly DateTime Started = DateTime.Now;   // set once at run time}

const values must be known when compiling (numbers, strings). Use static readonly for values calculated at run time, or for objects.

Static constructors

StaticCtor.cs
public static class SteelTable{    public static readonly Dictionary<string, double> KgPerMetre;     static SteelTable()          // runs once, automatically, before first use    {        KgPerMetre = new() { ["IPE200"] = 22.4, ["IPE300"] = 42.2 };    }}
Quick check

Why can’t a static method use this?

Quick check

Which of these is a static method call?

Practice

Create a static class Geometry with static methods CircleArea(double r) and CylinderVolume(double r, double h) (use Math.PI). Print the volume of a pipe with radius 0.1 m and length 6 m, to 4 decimals.

Show the solution
Solution.cs
public static class Geometry{    public static double CircleArea(double r) => Math.PI * r * r;    public static double CylinderVolume(double r, double h) => CircleArea(r) * h;} Console.WriteLine(Geometry.CylinderVolume(0.1, 6).ToString("F4"));
Output
0.1885

Remember

  • Static members belong to the class: one copy, used via ClassName.Member.
  • Static methods can’t use this or instance fields.
  • Static classes hold helpers and can’t be instantiated.
  • Prefer constants and stateless static methods; avoid mutable static state.
0 of 60 lessons completed