Bird
Raised Fist0
C Sharp (C#)programming~10 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main purpose of an instance field in a C# class?
easy
A. To store data unique to each object created from the class
B. To define a method that all objects share
C. To create a temporary variable inside a method
D. To hold data shared by all objects of the class

Solution

  1. Step 1: Understand what instance fields represent

    Instance fields hold data that belongs to each individual object, not shared across all objects.
  2. Step 2: Differentiate from static fields and methods

    Static fields hold shared data, methods define behavior, and local variables are temporary inside methods.
  3. Final Answer:

    To store data unique to each object created from the class -> Option A
  4. Quick Check:

    Instance field = unique object data [OK]
Hint: Instance fields hold unique data per object, not shared [OK]
Common Mistakes:
  • Confusing instance fields with static fields
  • Thinking methods are instance fields
  • Mixing local variables with instance fields
2. Which of the following is the correct way to declare an instance field named count of type int inside a C# class?
easy
A. static int count;
B. int count() {}
C. void count;
D. int count;

Solution

  1. Step 1: Identify correct syntax for instance field declaration

    Instance fields are declared with a type and name, without static keyword or parentheses.
  2. 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.
  3. Final Answer:

    int count; -> Option D
  4. Quick Check:

    Instance field syntax = type + name [OK]
Hint: Instance fields: type and name, no parentheses or static [OK]
Common Mistakes:
  • Using static keyword for instance fields
  • Adding parentheses like a method
  • Using void as a type for fields
3. What will be the output of this C# code?
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());
medium
A. 0
B. 2
C. 1
D. Compilation error

Solution

  1. Step 1: Trace the method calls on the object

    The object c calls Increment() twice, each increasing count by 1.
  2. Step 2: Check the value returned by GetCount()

    After two increments, count is 2, so GetCount() returns 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    2 increments = count 2 [OK]
Hint: Each Increment adds 1; two calls mean count is 2 [OK]
Common Mistakes:
  • Forgetting that count starts at 0
  • Assuming Increment does not change count
  • Confusing method return types
4. Identify the error in this C# class that tries to track a score:
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());
medium
A. No error; code runs and prints 5
B. score should be declared static
C. AddPoints method should return int
D. score is not initialized and may have a default value

Solution

  1. Step 1: Check field initialization rules in C#

    Instance fields like score default to 0 if not explicitly initialized.
  2. Step 2: Verify method behavior and output

    AddPoints adds points correctly, and GetScore returns the updated score. The code prints 5 as expected.
  3. Final Answer:

    No error; code runs and prints 5 -> Option A
  4. Quick Check:

    Uninitialized int defaults to 0 in C# [OK]
Hint: Instance int fields default to 0 if not set [OK]
Common Mistakes:
  • Thinking uninitialized int fields cause errors
  • Believing AddPoints must return a value
  • Confusing static and instance fields
5. You want to create a class 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;
  }
}
hard
A. Incorrect: Deposit and Withdraw should be static methods
B. Incorrect: balance should be static to share across accounts
C. Correct design: instance field stores balance, methods update and read it safely
D. Incorrect: balance should be public to allow direct access

Solution

  1. 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.
  2. Step 2: Verify methods safely update and provide access

    Deposit and Withdraw check amounts before changing balance, and GetBalance returns current balance safely.
  3. Final Answer:

    Correct design: instance field stores balance, methods update and read it safely -> Option C
  4. Quick Check:

    Instance field + safe methods = correct state management [OK]
Hint: Use private instance fields with methods to control access [OK]
Common Mistakes:
  • Making balance static, sharing state wrongly
  • Using static methods that can't access instance fields
  • Making balance public, breaking encapsulation