Static vs Instance Design
Decide when static state is appropriate.
A Design Decision
Choosing static vs instance is a design choice. The key question: does the behavior depend on per-object state, or only on its inputs?
using System;
class Program
{
// Depends only on inputs -> good static method
static int Max(int a, int b) => a > b ? a : b;
static void Main()
{
Console.WriteLine(Max(3, 8));
}
}Use Static for Stateless Logic
If a method needs no instance fields and just transforms inputs, make it static. Math helpers and formatters are prime examples.
using System;
static class Convert2
{
public static double MilesToKm(double miles) => miles * 1.60934;
}
class Program
{
static void Main()
{
Console.WriteLine(Convert2.MilesToKm(10).ToString("0.0") + " km");
}
}All lessons in this course
- Static Methods and Fields
- Static Classes for Utilities
- Constants and readonly Fields
- Static vs Instance Design