Static vs Instance ā”
Shared vs Personal - What Belongs to Everyone vs Each Person?
Hey There! Ready to Learn Static vs Instance? šÆ
Static and Instance are two types of members in C#. It's like the difference between something shared by everyone vs something that belongs to just one person.
- š« School Name is SHARED by everyone (static)
- šØāš Student Name belongs to each student (instance)
- ā Explain static vs instance like a pro
- ā Use static members (shared stuff)
- ā Use instance members (personal stuff)
- ā Know when to use each
- ā Build better, cleaner code
Part 1: What's the Difference? (The Easy Way)
š„ Static - Shared by Everyone
Static members belong to the class itself, not to any specific object.
- ā One copy shared by all
- ā Accessed through the class name
- ā Like a school name - everyone uses the same one
Math.PI - everyone uses the same Pi!
š¤ Instance - Personal to Each
Instance members belong to each object individually.
- ā Separate copies for each object
- ā Accessed through an object variable
- ā Like a student name - each student has their own
person.Name - each person has their own name!
- Static = Class level (one for all)
- Instance = Object level (one per object)
Part 2: Instance Members - Personal Stuff
Instance members are like personal belongings - each object has its own copy.
š Instance Fields
public class Person
{
// Each person has their own Name and Age
public string Name { get; set; }
public int Age { get; set; }
}
Each Person object has its own Name and Age!
šÆ Using Instance Members
// Create two people
Person person1 = new Person();
person1.Name = "Alice";
person1.Age = 25;
Person person2 = new Person();
person2.Name = "Bob";
person2.Age = 30;
// Each has their own values!
ā person1 and person2 have different values
Person p = new Person(); ā p.Name works ā
Person.Name doesn't work ā (needs an object)
Part 3: Static Members - Shared Stuff
Static members are like shared resources - one copy for everyone.
š Static Fields
public class School
{
// Shared by ALL students
public static string SchoolName = "C# Academy";
// Each student has their own
public string StudentName { get; set; }
}
One SchoolName for ALL students!
šÆ Using Static Members
// ā
Access through class name
Console.WriteLine(School.SchoolName); // "C# Academy"
// ā Can't access through object
School s = new School();
// s.SchoolName doesn't work!
š Static vs Instance - Visual Comparison
| Feature | Static | Instance |
|---|---|---|
| Belongs to | Class | Object |
| How many copies | One (shared) | Many (one per object) |
| How to access | ClassName.Member |
object.Member |
| Example | Math.PI |
person.Name |
Part 4: Static Methods - Utility Functions
š Static Method Example
public class MathHelper
{
// Static method - no object needed
public static int Add(int a, int b)
{
return a + b;
}
// Instance method - needs an object
private int result;
public void AddToResult(int value)
{
result += value;
}
}
šÆ Using Static Methods
// ā
No object needed!
int sum = MathHelper.Add(5, 3);
Console.WriteLine(sum); // 8
// ā Need an object for instance method
MathHelper helper = new MathHelper();
helper.AddToResult(10);
- ā
Utility functions (like
Math.Sqrt()) - ā No object data needed
- ā Helper methods
Part 5: Static Constructor - One-Time Setup
š Static Constructor
public class Config
{
public static string AppName;
public static string Version;
// Runs ONCE when class is first used
static Config()
{
AppName = "MyApp";
Version = "1.0.0";
Console.WriteLine("āļø Config loaded!");
}
}
šÆ When It Runs
// Static constructor runs HERE
Console.WriteLine(Config.AppName); // "MyApp"
// Static constructor already ran
Console.WriteLine(Config.Version); // "1.0.0"
- ā Runs ONCE (not every time)
- ā No parameters allowed
- ā Used for one-time setup
Part 6: Static Classes - Pure Utility
š Static Class
public static class FileHelper
{
// All members MUST be static
public static void WriteFile(string path)
{
Console.WriteLine($"Writing to {path}");
}
}
š« Cannot create FileHelper objects!
ā Using Static Class
// ā
Use directly through class name
FileHelper.WriteFile("data.txt");
// ā Can't do this:
// FileHelper helper = new FileHelper();
- ā
Math -
Math.Sqrt() - ā
File helpers -
File.ReadAllText() - ā
Convert -
Convert.ToInt32()
Part 7: Real-World Example - Bank System š°
Let's build a Bank System showing static and instance members!
// Bank System - Static vs Instance
public class Bank
{
// šµ STATIC - Shared by all accounts
public static string BankName = "C# National Bank";
private static int totalAccounts = 0;
private static double interestRate = 0.05;
// š¢ INSTANCE - Belongs to each account
public string AccountNumber { get; private set; }
public string Owner { get; set; }
public decimal Balance { get; private set; }
// Static method - shared functionality
public static int GetTotalAccounts() => totalAccounts;
public static void SetInterestRate(double rate)
{
if (rate >= 0) interestRate = rate;
}
// Constructor - creates new account
public Bank(string owner, decimal initial)
{
Owner = owner;
Balance = initial;
AccountNumber = GenerateAccountNumber();
totalAccounts++;
}
// Private static method
private static string GenerateAccountNumber()
{
return $"ACC-{DateTime.Now.Year}-{totalAccounts + 1:D4}";
}
// Instance methods - per account
public void Deposit(decimal amount)
{
if (amount > 0) Balance += amount;
}
public bool Withdraw(decimal amount)
{
if (amount > 0 && amount <= Balance)
{
Balance -= amount;
return true;
}
return false;
}
public void ApplyInterest()
{
Balance += Balance * (decimal)interestRate;
}
public void DisplayInfo()
{
Console.WriteLine($"š¦ {BankName}");
Console.WriteLine($"š Account: {AccountNumber}");
Console.WriteLine($"š¤ Owner: {Owner}");
Console.WriteLine($"š° Balance: ${Balance:F2}");
Console.WriteLine($"š Total Accounts: {GetTotalAccounts()}");
}
}
// Program.cs - Testing the Bank
class Program
{
static void Main()
{
Console.WriteLine("š¦ WELCOME TO THE BANK\n");
// Static members - shared
Console.WriteLine($"šļø Bank Name: {Bank.BankName}");
Console.WriteLine($"š Interest Rate: 5%\n");
// Create accounts - instance
Bank account1 = new Bank("John Doe", 1000.00m);
Bank account2 = new Bank("Jane Smith", 2000.00m);
// Instance operations
account1.Deposit(500.00m);
account2.Withdraw(200.00m);
account1.ApplyInterest();
// Display info
account1.DisplayInfo();
Console.WriteLine();
account2.DisplayInfo();
// Static members - shared
Console.WriteLine($"\nš Total Accounts: {Bank.GetTotalAccounts()}");
}
}
- ā Static: BankName, totalAccounts, interestRate (shared)
- ā Instance: AccountNumber, Owner, Balance (personal)
- ā Static Methods: GetTotalAccounts(), SetInterestRate()
- ā Instance Methods: Deposit(), Withdraw(), ApplyInterest()
Part 8: Let's Practice! š®
Track products and inventory with both shared and personal data.
š About This Application
This is a Store Inventory System like:
- šŖ Walmart - Track thousands of products
- š¦ Amazon - Manage inventory across warehouses
- šļø Local Store - Track stock and sales
Each product has personal data (name, price) and shared data (store name, total products):
- ā All products share the same Store Name
- ā Each product has its own Name, Price, Quantity
- ā Track Total Products in the system
Your Mission:
-
Class: Product
- š¢ Instance - Id, Name, Price, Quantity
- šµ Static - StoreName, totalProducts
- šµ Static Method - GetTotalProducts()
- š¢ Instance Method - AddStock(), RemoveStock()
- š¢ Instance Method - DisplayInfo()
-
Program.cs:
- Create 3+ products
- Add/remove stock
- Display product info
- Show total products
š” What You're Learning:
- ā Static = Store Name, Total Products (shared)
- ā Instance = Product details (personal)
- ā Static Method = Get total products
- ā Instance Method = Manage each product
// ===== PRODUCT INVENTORY SYSTEM =====
// This shows static vs instance members in action
public class Product
{
// šµ STATIC MEMBERS - Shared by all products
public static string StoreName = "C# Superstore";
private static int totalProducts = 0;
private static int nextId = 1000;
// š¢ INSTANCE MEMBERS - Belongs to each product
public int Id { get; private set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; private set; }
// šµ Static method - shared functionality
public static int GetTotalProducts() => totalProducts;
public static void ResetInventory()
{
totalProducts = 0;
nextId = 1000;
Console.WriteLine("š Inventory reset!");
}
// š¢ Constructor - creates new product
public Product(string name, decimal price, int quantity)
{
Name = name;
Price = price;
Quantity = quantity;
Id = GenerateId();
totalProducts++;
}
// šµ Private static helper
private static int GenerateId() => ++nextId;
// š¢ Instance methods - per product
public void AddStock(int amount)
{
if (amount > 0) Quantity += amount;
}
public bool RemoveStock(int amount)
{
if (amount > 0 && amount <= Quantity)
{
Quantity -= amount;
return true;
}
return false;
}
public decimal GetTotalValue() => Price * Quantity;
public void DisplayInfo()
{
Console.WriteLine($"šŖ {StoreName} - Product #{Id}");
Console.WriteLine($"š¦ {Name}");
Console.WriteLine($"š° ${Price:F2}");
Console.WriteLine($"š Quantity: {Quantity}");
Console.WriteLine($"šµ Total Value: ${GetTotalValue():F2}");
Console.WriteLine();
}
}
// Program.cs - Inventory System
class Program
{
static void Main()
{
Console.WriteLine("š¦ PRODUCT INVENTORY SYSTEM");
Console.WriteLine("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n");
// Static member - store name
Console.WriteLine($"šŖ Store: {Product.StoreName}\n");
// Create products (instance)
Product product1 = new Product("Laptop", 999.99m, 5);
Product product2 = new Product("Mouse", 25.50m, 20);
Product product3 = new Product("Keyboard", 45.00m, 15);
// Instance operations
product1.AddStock(2); // Add 2 more laptops
product2.RemoveStock(5); // Sell 5 mice
// Display all products
product1.DisplayInfo();
product2.DisplayInfo();
product3.DisplayInfo();
// Static method - total products
Console.WriteLine($"š Total Products: {Product.GetTotalProducts()}");
Console.WriteLine($"šŖ Store: {Product.StoreName}");
}
}