Instance vs Static Data
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 15 of 70.
Now that you understand static members, let's clarify when to use instance data versus static data. This decision shapes how your class stores and shares information.
Instance data belongs to each object individually. Every object gets its own copy, and changes to one object don't affect others:
public class BankAccount
{
public string Owner { get; set; } // Instance - unique per account
public decimal Balance { get; set; } // Instance - unique per account
}Each BankAccount has its own owner and balance. That makes sense because different accounts hold different amounts for different people.
Static data belongs to the class itself and is shared across all instances:
public class BankAccount
{
public static decimal InterestRate = 0.05m; // Static - same for all
public static int TotalAccounts = 0; // Static - tracks all accounts
public string Owner { get; set; }
public decimal Balance { get; set; }
}The interest rate applies equally to every account, so it makes sense as static. The total account counter tracks class-wide information, not individual account data.
A simple rule: if the data describes a specific object, make it instance. If it describes the class as a whole or should be shared, make it static. Mixing them incorrectly leads to bugs where data unexpectedly changes across objects or isn't accessible when needed.
Challenge
EasyLet's build a game session tracker that demonstrates the difference between data that belongs to individual players versus data shared across the entire game.
You'll create two files to organize your code:
Player.cs: Define aPlayerclass in theGameSessionnamespace. Each player has their ownUsername(string) andScore(int) - these are unique to each player. The class should also track information that applies to all players: a static fieldGameName(string) that stores the name of the game everyone is playing, and a static fieldTotalPlayers(int) that counts how many players have joined. Include a constructor that takes the username and starting score, and automatically increments the total player count. Add a static methodSetGameName(string name)to configure the game name.Program.cs: In your main file, set up the game and create players based on input. First set the game name, then create two players and display their individual information along with the shared game data.
You will receive five inputs:
- The game name
- First player's username
- First player's starting score
- Second player's username
- Second player's starting score
Print the output in this format:
Game: {GameName}
Player: {Username}, Score: {Score}
Player: {Username}, Score: {Score}
Total Players: {TotalPlayers}For example, if the inputs are BattleArena, DragonSlayer, 1500, ShadowNinja, and 2200, the output should be:
Game: BattleArena
Player: DragonSlayer, Score: 1500
Player: ShadowNinja, Score: 2200
Total Players: 2Think carefully about which data should be instance-based (different for each player) and which should be static (shared across all players). The game name and total player count describe the session as a whole, while username and score are unique to each individual.
Cheat sheet
Use instance data for properties that are unique to each object:
public class BankAccount
{
public string Owner { get; set; } // Each account has its own owner
public decimal Balance { get; set; } // Each account has its own balance
}Use static data for properties shared across all instances of a class:
public class BankAccount
{
public static decimal InterestRate = 0.05m; // Same for all accounts
public static int TotalAccounts = 0; // Tracks all accounts
public string Owner { get; set; }
public decimal Balance { get; set; }
}Decision rule: If the data describes a specific object, use instance data. If it describes the class as a whole or should be shared, use static data.
Try it yourself
using System;
namespace GameSession
{
class Program
{
public static void Main(string[] args)
{
// Read inputs
string gameName = Console.ReadLine();
string username1 = Console.ReadLine();
int score1 = Convert.ToInt32(Console.ReadLine());
string username2 = Console.ReadLine();
int score2 = Convert.ToInt32(Console.ReadLine());
// TODO: Set the game name using the static method
// TODO: Create two Player objects with the input data
// TODO: Print the output in the required format
// Game: {GameName}
// Player: {Username}, Score: {Score}
// Player: {Username}, Score: {Score}
// Total Players: {TotalPlayers}
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator3Class Architecture
Instance vs Static Data'readonly' & 'const' KeywordsBacking FieldsRecap - Bank Account Manager