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

Instance fields and state in C Sharp (C#) - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Instance Fields Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code with instance fields?

Consider the following C# class and code. What will be printed when the program runs?

C Sharp (C#)
class Counter {
    private int count = 0;
    public void Increment() {
        count++;
    }
    public int GetCount() {
        return count;
    }
}

var c1 = new Counter();
c1.Increment();
c1.Increment();
var c2 = new Counter();
c2.Increment();
Console.WriteLine(c1.GetCount());
Console.WriteLine(c2.GetCount());
A3\n1
B1\n1
C2\n1
D2\n2
Attempts:
2 left
💡 Hint

Remember each object has its own copy of instance fields.

Predict Output
intermediate
2:00remaining
What is the value of the instance field after method calls?

What will be the value of balance after running this code?

C Sharp (C#)
class BankAccount {
    private decimal balance = 100m;
    public void Deposit(decimal amount) {
        balance += amount;
    }
    public void Withdraw(decimal amount) {
        balance -= amount;
    }
    public decimal GetBalance() {
        return balance;
    }
}

var account = new BankAccount();
account.Deposit(50m);
account.Withdraw(30m);
var result = account.GetBalance();
Console.WriteLine(result);
A80
B120
C150
D100
Attempts:
2 left
💡 Hint

Think about adding and subtracting from the starting balance.

🔧 Debug
advanced
2:30remaining
Why does this instance field not update as expected?

Look at this code. Why does the count field not increase after calling Increment?

C Sharp (C#)
class Counter {
    private int count = 0;
    public void Increment() {
        int count = 0;
        count++;
    }
    public int GetCount() {
        return count;
    }
}

var c = new Counter();
c.Increment();
c.Increment();
Console.WriteLine(c.GetCount());
AThe instance field 'count' is reset to zero every time Increment is called.
BThe instance field 'count' is private and cannot be changed outside the class.
CThe Increment method does not have a return statement, so count is not updated.
DThe local variable 'count' inside Increment hides the instance field, so the instance field never changes.
Attempts:
2 left
💡 Hint

Check variable names inside the method and the class.

📝 Syntax
advanced
1:30remaining
Which option correctly declares and initializes an instance field?

Which of the following options correctly declares an instance field name of type string and initializes it to "Alice"?

Aprivate string name = "Alice";
B
string name;
name = "Alice";
C
private string name;
name = "Alice";
Dstring name = "Alice";
Attempts:
2 left
💡 Hint

Instance fields are declared inside the class but outside methods, with optional access modifiers and initialization.

🚀 Application
expert
3:00remaining
How many unique instance states exist after this code runs?

Given the class and code below, how many unique Person objects have different age values after execution?

C Sharp (C#)
class Person {
    public int age;
    public Person(int age) {
        this.age = age;
    }
}

var p1 = new Person(20);
var p2 = new Person(25);
var p3 = p1;
p3.age = 30;
var p4 = new Person(30);
var p5 = p2;
p5.age = 35;

var list = new List<Person> { p1, p2, p3, p4, p5 };
var uniqueAges = list.Select(p => p.age).Distinct().Count();
Console.WriteLine(uniqueAges);
A2
B4
C3
D5
Attempts:
2 left
💡 Hint

Remember that p3 and p1 refer to the same object, as do p5 and p2.

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