Static Fields & Methods
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 12 of 70.
So far, every field and method we've created belongs to individual objects. But sometimes you need data or behavior that belongs to the class itself, shared across all instances. That's where the static keyword comes in.
A static field is shared by all objects of a class. There's only one copy, no matter how many instances you create:
public class Player
{
public static int TotalPlayers = 0;
public string Name { get; set; }
public Player(string name)
{
Name = name;
TotalPlayers++;
}
}Every time a new Player is created, TotalPlayers increases. All players share this same counter.
A static method belongs to the class and can be called without creating an object:
public class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
// Called on the class, not an instance
int result = Calculator.Add(5, 3);Notice you access static members using the class name, not an object reference. Static methods cannot access instance fields or use this, since they don't belong to any specific object.
You've already used static members without realizing it. Console.WriteLine() is a static method, and Math.PI is a static field.
Challenge
EasyLet's build an order tracking system that uses static members to keep track of all orders placed across your application.
You'll create two files to organize your code:
Order.cs: Define anOrderclass in theOrderSystemnamespace. Each order should have an instance propertyOrderId(int) andCustomerName(string). The class should also track the total number of orders created using a static fieldTotalOrders, and provide a static methodGetNextOrderId()that returns the next available order ID (starting from 1). The constructor should accept a customer name, automatically assign the order ID using the static method, and increment the total orders count.Program.cs: In your main file, create orders based on input and display their details along with the total order count.
You will receive two inputs representing customer names for two separate orders.
For each order, print its details in this format:
Order #{OrderId} - Customer: {CustomerName}After creating both orders, print the total count:
Total Orders: {TotalOrders}For example, if the inputs are Alice and Bob, the output should be:
Order #1 - Customer: Alice
Order #2 - Customer: Bob
Total Orders: 2Cheat sheet
The static keyword creates members that belong to the class itself rather than to individual instances.
Static fields are shared across all objects of a class. Only one copy exists regardless of how many instances are created:
public class Player
{
public static int TotalPlayers = 0;
public string Name { get; set; }
public Player(string name)
{
Name = name;
TotalPlayers++;
}
}Static methods belong to the class and can be called without creating an object:
public class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
// Called on the class, not an instance
int result = Calculator.Add(5, 3);Static members are accessed using the class name, not an object reference. Static methods cannot access instance fields or use this since they don't belong to any specific object.
Common examples of static members include Console.WriteLine() (static method) and Math.PI (static field).
Try it yourself
using System;
using OrderSystem;
class Program
{
public static void Main(string[] args)
{
// Read customer names
string customer1 = Console.ReadLine();
string customer2 = Console.ReadLine();
// TODO: Create two Order objects with the customer names
// TODO: Print each order's details in the format:
// Order #{OrderId} - Customer: {CustomerName}
// TODO: Print the total orders count in the format:
// Total Orders: {TotalOrders}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator