Static and Instance Members in C#
The Shared vs Personal Belongings Story đźŹ
The Big Picture
Imagine a classroom. Some things belong to the whole class (like the whiteboard everyone shares), and some things belong to each student (like their own pencil case).
In C#, static members are like the whiteboard—shared by everyone. Instance members are like pencil cases—each object gets its own copy.
🎯 What We’ll Learn
- Static members – Shared stuff that belongs to the class itself
- Static constructors – Setting up shared stuff once
- The
thiskeyword – Pointing to “myself”
Part 1: Static Members
The Classroom Analogy
class Classroom
{
// Shared by ALL students
public static string SchoolName = "Sunny Academy";
// Each student has their own
public string StudentName;
}
Static = Shared. Everyone sees the same SchoolName.
Instance = Personal. Each student has their own StudentName.
How Static Members Work
// Access static member: ClassName.Member
Console.WriteLine(Classroom.SchoolName);
// Access instance member: object.Member
Classroom s1 = new Classroom();
s1.StudentName = "Emma";
Notice:
- Static: Use the class name directly
- Instance: Need to create an object first
Static Fields
A static field is one variable shared across all objects.
class Counter
{
public static int TotalCount = 0;
public Counter()
{
TotalCount++; // Every new object adds 1
}
}
new Counter(); // TotalCount = 1
new Counter(); // TotalCount = 2
new Counter(); // TotalCount = 3
Console.WriteLine(Counter.TotalCount); // 3
All three objects share the same counter!
Static Methods
A static method belongs to the class, not any object.
class MathHelper
{
public static int Add(int a, int b)
{
return a + b;
}
}
// No object needed!
int result = MathHelper.Add(5, 3); // 8
You’ve used this before: Console.WriteLine() and Math.Max() are static methods!
Static vs Instance: Quick Comparison
graph TD A[Class: BankAccount] --> B[Static: InterestRate<br/>Shared by ALL accounts] A --> C[Instance: Balance<br/>Each account has its own] B --> D[BankAccount.InterestRate] C --> E[myAccount.Balance]
| Feature | Static | Instance |
|---|---|---|
| Belongs to | Class | Object |
| Access via | ClassName | objectName |
| Memory | One copy | Many copies |
| Keyword | static |
(none) |
🎯 Static Members Rule
Static members cannot access instance members directly!
class Player
{
public string Name; // Instance
public static int PlayerCount = 0; // Static
// ❌ WRONG - static can't see instance
public static void ShowName()
{
Console.WriteLine(Name); // Error!
}
// âś… RIGHT - instance can see static
public void Show()
{
Console.WriteLine(PlayerCount); // Works!
}
}
Why? Static exists even when no objects exist. It doesn’t know which object’s Name you mean!
Part 2: Static Constructors
What’s a Static Constructor?
A static constructor runs once, automatically, before the class is used for the first time.
It’s like a setup crew that prepares the classroom before any students arrive.
Static Constructor Syntax
class Config
{
public static string AppName;
public static DateTime StartTime;
// Static constructor - no access modifier!
static Config()
{
AppName = "My Cool App";
StartTime = DateTime.Now;
Console.WriteLine("Config initialized!");
}
}
When Does It Run?
// First time you touch the class
Console.WriteLine(Config.AppName);
// Output: "Config initialized!"
// Output: "My Cool App"
// Already ran - won't run again
Console.WriteLine(Config.StartTime);
// Output: (time value only)
Key Points:
- Runs automatically (you don’t call it)
- Runs exactly once
- Runs before any static member is accessed
- Has no parameters and no access modifier
Static Constructor vs Regular Constructor
class Logger
{
public static string LogFile;
public string InstanceId;
// Static constructor: runs ONCE for the class
static Logger()
{
LogFile = "app.log";
Console.WriteLine("Static: Setting up log file");
}
// Instance constructor: runs for EACH object
public Logger()
{
InstanceId = Guid.NewGuid().ToString();
Console.WriteLine("Instance: New logger created");
}
}
var log1 = new Logger();
// Output: "Static: Setting up log file"
// Output: "Instance: New logger created"
var log2 = new Logger();
// Output: "Instance: New logger created"
// (Static constructor doesn't run again!)
Static Constructor Flow
graph TD A[First use of class] --> B[Static constructor runs] B --> C[Static fields initialized] C --> D[Class ready to use] D --> E[new Object created] E --> F[Instance constructor runs] F --> G[Object ready] E --> E
Part 3: The this Keyword
What is this?
The this keyword is like saying “me” or “myself”.
When you’re inside an object’s method, this refers to that specific object.
Basic Usage: Clarify Names
When parameter names match field names:
class Person
{
public string Name;
public int Age;
public Person(string Name, int Age)
{
// Without 'this', it's confusing!
// Which 'Name' is which?
this.Name = Name; // this.Name = field
this.Age = Age; // Age (right) = parameter
}
}
this.Name clearly means “my Name field”
Plain Name refers to the parameter
this in Action
class Cat
{
public string Name;
public Cat(string Name)
{
this.Name = Name;
}
public void Introduce()
{
Console.WriteLine(quot;I am {this.Name}");
}
}
Cat whiskers = new Cat("Whiskers");
Cat mittens = new Cat("Mittens");
whiskers.Introduce(); // "I am Whiskers"
mittens.Introduce(); // "I am Mittens"
Each cat’s this refers to itself!
Method Chaining with this
Return this to enable fluent style:
class Builder
{
public string Text = "";
public Builder Add(string s)
{
Text += s;
return this; // Return myself!
}
public Builder AddSpace()
{
Text += " ";
return this;
}
}
var b = new Builder();
b.Add("Hello").AddSpace().Add("World");
Console.WriteLine(b.Text); // "Hello World"
Each method returns the same object, so you can keep calling methods!
this Cannot Be Used in Static
class Demo
{
public int Value;
// ❌ WRONG
public static void StaticMethod()
{
this.Value = 10; // Error!
}
// âś… RIGHT
public void InstanceMethod()
{
this.Value = 10; // Works!
}
}
Why? Static methods don’t belong to any object. There’s no “myself” to refer to!
🎯 this Use Cases Summary
| Use Case | Example |
|---|---|
| Distinguish field from parameter | this.name = name; |
| Pass current object | SomeMethod(this); |
| Method chaining | return this; |
| Call another constructor | this(defaultValue) |
Putting It All Together
class BankAccount
{
// Static: shared by all accounts
public static decimal InterestRate;
public static int TotalAccounts = 0;
// Instance: each account has its own
public string Owner;
public decimal Balance;
// Static constructor: runs once
static BankAccount()
{
InterestRate = 0.05m;
Console.WriteLine("Bank system ready!");
}
// Instance constructor: runs per object
public BankAccount(string Owner)
{
this.Owner = Owner; // 'this' clarifies
this.Balance = 0;
TotalAccounts++; // Update shared count
}
// Instance method using static member
public decimal CalculateInterest()
{
return this.Balance * InterestRate;
}
}
// Static constructor runs now
var acc1 = new BankAccount("Alice");
var acc2 = new BankAccount("Bob");
Console.WriteLine(BankAccount.TotalAccounts); // 2
Console.WriteLine(BankAccount.InterestRate); // 0.05
🚀 Quick Recap
| Concept | What It Means |
|---|---|
| Static Field | One shared variable for all objects |
| Static Method | Method called on class, not object |
| Static Constructor | Runs once, sets up static stuff |
this Keyword |
“Myself” - the current object |
🎉 You Did It!
Now you understand:
- âś… Static members belong to the class (shared)
- âś… Instance members belong to objects (personal)
- âś… Static constructors run once automatically
- âś…
thismeans “the current object”
These concepts are the building blocks of every C# application. You’re ready to write cleaner, smarter code! 💪