DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: static Keyword

Meta Description: Learn the difference between instance fields and static fields in C#. Understand how static works with practical examples, covering scenarios like employee bonuses, store inventory, game high scores, and more. A complete guide to mastering staticin C#, including practice assignments for better understanding.

The static keyword is a fundamental concept in C# that can sometimes be confusing, especially when you're just starting. In this article, we will explore what static means, how it differs from regular instance fields, and why it is so useful. We'll also cover multiple practical examples to help you clearly understand these differences.

Instance Fields vs. Static Fields in C#

When we create a class, we can define fields and methods that represent the data and actions associated with that class. Fields can either be instance fields or static fields. Let’s first understand the difference between the two:

Instance Fields:
  • Belong to an Object: Each instance of a class has its own copy of an instance field.
  • Unique Values: Different objects can have different values for an instance field.
  • Accessed through an Object: You need to create an instance of the class to access an instance field.
Static Fields:
  • Belong to the Class: Static fields are shared among all instances of a class. Only one copy of a static field exists.
  • One Value for All: If a static field changes, it changes for all instances.
  • Accessed through the Class: Static fields are accessed using the class name, not through an object instance.

Example 1: Employee Bonus

Let’s take an example using an Employee class to differentiate between instance fields and static fields.

public class Employee
{
    public string Name; // Instance field
    public static double BonusRate = 0.1; // Static field
}
Enter fullscreen mode Exit fullscreen mode
  • Name is an instance field, meaning each Employee object has its own name.
  • BonusRate is a static field, which is shared among all employees.

Here's how it works in practice:

Employee emp1 = new Employee();
emp1.Name = "Alice";

Employee emp2 = new Employee();
emp2.Name = "Bob";

// Different instance fields
Console.WriteLine(emp1.Name); // Output: Alice
Console.WriteLine(emp2.Name); // Output: Bob

// Accessing the static field
Console.WriteLine(Employee.BonusRate); // Output: 0.1

// Update the static field
Employee.BonusRate = 0.2;

// Print the updated static field for both employees
Console.WriteLine(Employee.BonusRate); // Output: 0.2
Enter fullscreen mode Exit fullscreen mode

In this example, Name is unique for each employee, while BonusRate is shared across all employees.

Example 2: Store Inventory Tracking

Suppose we have a store that sells different items, and we want to keep track of the total inventory count across all items, as well as each item's stock.

public class StoreItem
{
    public string ItemName { get; set; } // Instance field for each item's name
    public int Stock { get; set; } // Instance field for each item's stock
    public static int TotalInventory = 0; // Static field for total inventory

    public StoreItem(string itemName, int stock)
    {
        ItemName = itemName;
        Stock = stock;
        TotalInventory += stock; // Increment total inventory
    }

    public void SellItem(int quantity)
    {
        if (quantity <= Stock)
        {
            Stock -= quantity;
            TotalInventory -= quantity; // Update the total inventory
            Console.WriteLine($"Sold {quantity} units of {ItemName}. Remaining stock: {Stock}");
        }
        else
        {
            Console.WriteLine($"Not enough stock for {ItemName}.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Testing the Example:

StoreItem item1 = new StoreItem("Laptop", 50);
StoreItem item2 = new StoreItem("Smartphone", 30);

Console.WriteLine($"Total Inventory: {StoreItem.TotalInventory}"); // Output: 80

item1.SellItem(10);
Console.WriteLine($"Total Inventory after selling: {StoreItem.TotalInventory}"); // Output: 70
Enter fullscreen mode Exit fullscreen mode
  • Stock is an instance field specific to each item.
  • TotalInventory is a static field shared among all StoreItem objects.

Example 3: Counting Active Users in a Chat Application

Let's say we're building a chat application and want to keep track of the number of active users.

public class ChatUser
{
    public string Username { get; set; } // Instance field for username
    public static int ActiveUsers = 0; // Static field to count active users

    public ChatUser(string username)
    {
        Username = username;
        ActiveUsers++; // Increment active users when a new user joins
    }

    public void Logout()
    {
        ActiveUsers--; // Decrement active users when a user logs out
        Console.WriteLine($"{Username} logged out. Active users: {ActiveUsers}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Testing the Example:

ChatUser user1 = new ChatUser("Alice");
ChatUser user2 = new ChatUser("Bob");

Console.WriteLine($"Active Users: {ChatUser.ActiveUsers}"); // Output: 2

user1.Logout();
Console.WriteLine($"Active Users after logout: {ChatUser.ActiveUsers}"); // Output: 1
Enter fullscreen mode Exit fullscreen mode
  • Username is unique for each chat user.
  • ActiveUsers is a static field that tracks the number of active users.

Example 4: Car Manufacturer

Consider a car manufacturing scenario where you want to track each car’s model and color, and also count how many cars have been manufactured in total.

public class Car
{
    public string Model { get; set; } // Instance field for car model
    public string Color { get; set; } // Instance field for car color
    public static int TotalCarsManufactured = 0; // Static field for total cars manufactured

    public Car(string model, string color)
    {
        Model = model;
        Color = color;
        TotalCarsManufactured++; // Increment total cars manufactured
    }

    public static void DisplayTotalCars()
    {
        Console.WriteLine($"Total cars manufactured: {TotalCarsManufactured}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Testing the Example:

Car car1 = new Car("Sedan", "Red");
Car car2 = new Car("SUV", "Black");

Car.DisplayTotalCars(); // Output: Total cars manufactured: 2
Enter fullscreen mode Exit fullscreen mode
  • Model and Color are instance fields unique to each car.
  • TotalCarsManufactured is a static field shared by all cars to keep track of production.

Example 5: School Students Tracking

Suppose you want to manage students in a school and count the total number of students while maintaining individual information.

public class Student
{
    public string Name { get; set; } // Instance field for student name
    public int Grade { get; set; } // Instance field for student grade
    public static int TotalStudents = 0; // Static field to count total students

    public Student(string name, int grade)
    {
        Name = name;
        Grade = grade;
        TotalStudents++;
    }

    public static void DisplayTotalStudents()
    {
        Console.WriteLine($"Total number of students: {TotalStudents}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Testing the Example:

Student student1 = new Student("Emma", 9);
Student student2 = new Student("Liam", 10);

Student.DisplayTotalStudents(); // Output: Total number of students: 2
Enter fullscreen mode Exit fullscreen mode
  • Name and Grade are unique for each student.
  • TotalStudents is shared to keep track of how many students are enrolled.

Example 6: Game High Score Tracker

Imagine a video game where you want to keep track of each player's score and the highest score achieved.

public class GamePlayer
{
    public string PlayerName { get; set; } // Instance field for player name
    public int CurrentScore { get; set; } // Instance field for player's current score
    public static int HighScore = 0; // Static field for the highest score

    public GamePlayer(string playerName)
    {
        PlayerName = playerName;
        CurrentScore = 0;
    }

    public void UpdateScore(int points)
    {
        CurrentScore += points;
        if (CurrentScore > HighScore)
        {
            HighScore = CurrentScore; // Update high score if current score exceeds it
        }
    }

    public static void DisplayHighScore()
    {
        Console.WriteLine($"The highest score is: {HighScore}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Testing the Example:

GamePlayer player1 = new GamePlayer("PlayerOne");
player1.UpdateScore(100);

GamePlayer player2 = new GamePlayer("PlayerTwo");
player2.UpdateScore(150);

GamePlayer.DisplayHighScore(); // Output: The highest score is: 150
Enter fullscreen mode Exit fullscreen mode
  • PlayerName and CurrentScore are unique for each player.
  • HighScore is shared across all players to keep track of the top score.

Key Takeaways

  1. Instance Fields are unique to

each object, allowing each instance to have its own value.

  1. Static Fields are shared by all instances of a class, which means they maintain a common value across all objects.
  2. Static Methods also belong to the class itself, and they can access only static fields.

Analogy to Make It Clear:

  • Instance Fields: Think of instance fields like each student having their own notebook—each notebook has unique notes.
  • Static Fields: Think of static fields like a shared chalkboard in the classroom—everyone can see and change what's written there.

Practice Assignments

To reinforce your understanding, try solving these practice assignments:

  1. Easy: Create a LibraryBook class with a TotalBooks static field that counts the number of books created.
  2. Medium: Create a BankAccount class with a static InterestRate field. Update the interest rate for all accounts using a static method.
  3. Difficult: Create an OnlineStore class with TotalSales as a static field and implement methods for tracking individual item sales and total store sales.

Understanding these differences and how to use instance and static fields will help you write more efficient and organized C# code. Try out the assignments and see the power of static in action!

Top comments (0)