Mastering C# Fundamentals: static Keyword
mohamed Tayel
Posted on September 30, 2024
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 static
in 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
}
-
Name
is an instance field, meaning eachEmployee
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
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}.");
}
}
}
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
-
Stock
is an instance field specific to each item. -
TotalInventory
is a static field shared among allStoreItem
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}");
}
}
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
-
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}");
}
}
Testing the Example:
Car car1 = new Car("Sedan", "Red");
Car car2 = new Car("SUV", "Black");
Car.DisplayTotalCars(); // Output: Total cars manufactured: 2
-
Model
andColor
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}");
}
}
Testing the Example:
Student student1 = new Student("Emma", 9);
Student student2 = new Student("Liam", 10);
Student.DisplayTotalStudents(); // Output: Total number of students: 2
-
Name
andGrade
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}");
}
}
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
-
PlayerName
andCurrentScore
are unique for each player. -
HighScore
is shared across all players to keep track of the top score.
Key Takeaways
- Instance Fields are unique to
each object, allowing each instance to have its own value.
- Static Fields are shared by all instances of a class, which means they maintain a common value across all objects.
- 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:
-
Easy: Create a
LibraryBook
class with aTotalBooks
static field that counts the number of books created. -
Medium: Create a
BankAccount
class with a staticInterestRate
field. Update the interest rate for all accounts using a static method. -
Difficult: Create an
OnlineStore
class withTotalSales
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!
Posted on September 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.