0
0
C Sharp (C#)programming~10 mins

Instance fields and state in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Instance fields and state
Create Object
Allocate Instance Fields
Initialize Fields
Object Holds State
Use Object Methods
Modify Fields -> Change State
State Persists in Object
When you create an object, it gets its own copy of instance fields that hold its state. Methods can read or change this state.
Execution Sample
C Sharp (C#)
class Counter {
  int count = 0;
  public void Increment() { count++; }
  public int GetCount() { return count; }
}

var c = new Counter();
c.Increment();
c.GetCount();
This code creates a Counter object, increases its count by 1, then gets the current count.
Execution Table
StepActionField 'count' ValueOutput
1Create Counter object0
2Call Increment()1
3Call GetCount()11
4End1Final count is 1
💡 No more actions; program ends with count = 1
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
countN/A0111
Key Moments - 2 Insights
Why does 'count' keep its value between method calls?
Because 'count' is an instance field stored inside the object, it keeps its value as long as the object exists (see steps 2 and 3 in execution_table).
What happens if we create a second Counter object?
Each object has its own 'count' field starting at 0, so they do not share state. This is why instance fields belong to individual objects.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'count' after step 2?
A0
B2
C1
DUndefined
💡 Hint
Check the 'Field count Value' column in row for step 2.
At which step does the method GetCount() return the value 1?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Output' column in the execution table.
If we create a new Counter object and call GetCount() immediately, what would be the output?
AUndefined
B0
C1
DError
💡 Hint
Instance fields start at their initial value when a new object is created (see step 1).
Concept Snapshot
Instance fields are variables inside an object.
Each object has its own copy, holding its state.
Methods can read or change these fields.
State persists as long as the object exists.
Creating new objects creates new independent states.
Full Transcript
When you create an object in C#, it gets its own instance fields. These fields hold the object's state. For example, a Counter object has a 'count' field starting at 0. When you call Increment(), it increases 'count' by 1. Calling GetCount() returns the current 'count'. This state stays inside the object between method calls. If you create another Counter object, it has its own separate 'count' starting at 0. Instance fields belong to each object individually and keep their values as long as the object exists.