Static vs Instance ⚔

Shared vs Personal - What Belongs to Everyone vs Each Person?

Beginner Friendly 20 min read Lesson 9 of 11

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.

Quick Question: Think about a school!
  • šŸ« School Name is SHARED by everyone (static)
  • šŸ‘Øā€šŸŽ“ Student Name belongs to each student (instance)
šŸŽÆ After this lesson, you'll be able to:
  • āœ… 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
Example: 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
Example: person.Name - each person has their own name!
Remember:
  • Static = Class level (one for all)
  • Instance = Object level (one per object)
šŸ˜‚ Fun Joke: Why did the static method break up with the instance method? Because it couldn't handle the personal space! (Okay, I'll stop šŸ˜…)

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

Key Point: You MUST create an object to use instance members!
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!
Remember: Static members use the class name, not an object!
šŸ“Š 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);
When to use static methods:
  • āœ… Utility functions (like Math.Sqrt())
  • āœ… No object data needed
  • āœ… Helper methods

Part 5: Static Constructor - One-Time Setup

What's a Static Constructor? It runs ONCE when the class is first used.
šŸ“ 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"
Key Points:
  • āœ… Runs ONCE (not every time)
  • āœ… No parameters allowed
  • āœ… Used for one-time setup

Part 6: Static Classes - Pure Utility

What's a Static Class? A class that cannot be created - it's just a container for static members!
šŸ“ 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();
When to use static classes:
  • āœ… 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()}");
    }
}
šŸŽ‰ What this shows:
  • āœ… Static: BankName, totalAccounts, interestRate (shared)
  • āœ… Instance: AccountNumber, Owner, Balance (personal)
  • āœ… Static Methods: GetTotalAccounts(), SetInterestRate()
  • āœ… Instance Methods: Deposit(), Withdraw(), ApplyInterest()
šŸ˜‚ Bank Joke: Why did the static variable break up with the instance variable? Because it couldn't handle the personal space! (Okay, I'll stop now šŸ˜…)

Part 8: Let's Practice! šŸŽ®

What You're Building: A Product Inventory System for a store!
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:
  1. Class: Product
    • 🟢 Instance - Id, Name, Price, Quantity
    • šŸ”µ Static - StoreName, totalProducts
    • šŸ”µ Static Method - GetTotalProducts()
    • 🟢 Instance Method - AddStock(), RemoveStock()
    • 🟢 Instance Method - DisplayInfo()
  2. 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
Result: A complete inventory system with both shared and personal data!

šŸŽ‰ What You Learned Today!

Static
Shared by everyone
Instance
Personal to each
Static Methods
Utility functions
Static Classes
Pure containers
Real Example
Bank System! šŸ’°
Inventory System
Store Example! šŸ›’
Smart Choice
Static vs Instance
Test Your Knowledge - Take Quiz