Instance fields store information unique to each object. They help keep track of an object's state over time.
Instance fields and state in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
class ClassName { private int fieldName; // instance field public ClassName(int initialValue) { fieldName = initialValue; } }
Instance fields are declared inside a class but outside any method.
Each object (instance) of the class has its own copy of these fields.
color field that stores each car's color.class Car { private string color; // instance field public Car(string carColor) { color = carColor; } }
count to keep track of a counter's state.class Counter { private int count = 0; // instance field with default value public void Increment() { count++; } public int GetCount() { return count; } }
This program creates a LightBulb object that remembers if it is on or off using an instance field. It shows how the state changes when switching on and off.
using System; class LightBulb { private bool isOn; // instance field to store state public LightBulb() { isOn = false; // starts off } public void SwitchOn() { isOn = true; } public void SwitchOff() { isOn = false; } public void ShowState() { Console.WriteLine(isOn ? "The light bulb is ON." : "The light bulb is OFF."); } } class Program { static void Main() { LightBulb bulb = new LightBulb(); bulb.ShowState(); bulb.SwitchOn(); bulb.ShowState(); bulb.SwitchOff(); bulb.ShowState(); } }
Instance fields keep data for each object separately, so changing one object's field does not affect others.
Use private to hide fields and protect data inside the object.
Access and change instance fields through methods or properties to control how data is used.
Instance fields store data unique to each object.
They help objects remember their own state over time.
Use methods to safely read or change instance fields.
Practice
instance field in a C# class?Solution
Step 1: Understand what instance fields represent
Instance fields hold data that belongs to each individual object, not shared across all objects.Step 2: Differentiate from static fields and methods
Static fields hold shared data, methods define behavior, and local variables are temporary inside methods.Final Answer:
To store data unique to each object created from the class -> Option AQuick Check:
Instance field = unique object data [OK]
- Confusing instance fields with static fields
- Thinking methods are instance fields
- Mixing local variables with instance fields
count of type int inside a C# class?Solution
Step 1: Identify correct syntax for instance field declaration
Instance fields are declared with a type and name, without static keyword or parentheses.Step 2: Check each option
static int count; is static, not instance. void count; uses void which is invalid for fields. int count() {} looks like a method, not a field.Final Answer:
int count; -> Option DQuick Check:
Instance field syntax = type + name [OK]
- Using static keyword for instance fields
- Adding parentheses like a method
- Using void as a type for fields
class Counter {
private int count = 0;
public void Increment() {
count++;
}
public int GetCount() {
return count;
}
}
var c = new Counter();
c.Increment();
c.Increment();
Console.WriteLine(c.GetCount());Solution
Step 1: Trace the method calls on the object
The objectccallsIncrement()twice, each increasingcountby 1.Step 2: Check the value returned by
After two increments,GetCount()countis 2, soGetCount()returns 2.Final Answer:
2 -> Option BQuick Check:
2 increments = count 2 [OK]
- Forgetting that count starts at 0
- Assuming Increment does not change count
- Confusing method return types
class Game {
int score;
public void AddPoints(int points) {
score = score + points;
}
public int GetScore() {
return score;
}
}
var g = new Game();
g.AddPoints(5);
Console.WriteLine(g.GetScore());Solution
Step 1: Check field initialization rules in C#
Instance fields likescoredefault to 0 if not explicitly initialized.Step 2: Verify method behavior and output
AddPointsadds points correctly, andGetScorereturns the updated score. The code prints 5 as expected.Final Answer:
No error; code runs and prints 5 -> Option AQuick Check:
Uninitialized int defaults to 0 in C# [OK]
- Thinking uninitialized int fields cause errors
- Believing AddPoints must return a value
- Confusing static and instance fields
BankAccount that remembers the balance for each account. Which design correctly uses instance fields to track the balance and safely update it?class BankAccount {
private decimal balance;
public BankAccount(decimal initial) {
balance = initial;
}
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 decimal GetBalance() {
return balance;
}
}Solution
Step 1: Check if balance is instance field and encapsulated
Balance is private instance field, unique per object, which is correct for tracking each account.Step 2: Verify methods safely update and provide access
Deposit and Withdraw check amounts before changing balance, and GetBalance returns current balance safely.Final Answer:
Correct design: instance field stores balance, methods update and read it safely -> Option CQuick Check:
Instance field + safe methods = correct state management [OK]
- Making balance static, sharing state wrongly
- Using static methods that can't access instance fields
- Making balance public, breaking encapsulation
