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
Methods that operate on state
📖 Scenario: You are creating a simple bank account program. The account has a balance that changes when you deposit or withdraw money.
🎯 Goal: Build a class with methods that change the account balance and show the current balance.
📋 What You'll Learn
Create a class called BankAccount with a private balance variable.
Add a method Deposit that adds money to balance.
Add a method Withdraw that subtracts money from balance.
Add a method GetBalance that returns the current balance.
Create an instance of BankAccount and use the methods to change and show the balance.
💡 Why This Matters
🌍 Real World
Bank accounts, game scores, or any object that keeps track of changing information use methods to update and read their state.
💼 Career
Understanding how to write methods that operate on an object's state is essential for software development, especially in object-oriented programming.
Progress0 / 4 steps
1
Create the BankAccount class with a balance variable
Create a class called BankAccount with a private integer variable balance set to 0.
C Sharp (C#)
Hint
Use class BankAccount and inside it declare private int balance = 0;.
2
Add Deposit and Withdraw methods
Add a public method Deposit that takes an integer amount and adds it to balance. Add a public method Withdraw that takes an integer amount and subtracts it from balance.
C Sharp (C#)
Hint
Write two methods: Deposit adds amount to balance, Withdraw subtracts amount from balance.
3
Add GetBalance method
Add a public method GetBalance that returns the current balance as an integer.
C Sharp (C#)
Hint
Write a method GetBalance that returns the value of balance.
4
Create an instance and show the balance
Create an instance of BankAccount called account. Call Deposit(100) and Withdraw(30) on account. Then print the result of account.GetBalance().
C Sharp (C#)
Hint
Create account, call Deposit(100), Withdraw(30), then print account.GetBalance().
Practice
(1/5)
1. What is the main purpose of methods that operate on state in a C# class?
easy
A. To perform calculations without changing any data
B. To allow objects to keep and change their own data safely
C. To handle user input from the console
D. To create new classes from existing ones
Solution
Step 1: Understand what 'state' means in programming
State refers to the data stored inside an object that can change over time.
Step 2: Identify the role of methods operating on state
These methods allow the object to update or read its own data safely, keeping control inside the object.
Final Answer:
To allow objects to keep and change their own data safely -> Option B
Quick Check:
Methods on state = safe data change inside object [OK]
Hint: Think: methods change or read object's own data [OK]
Common Mistakes:
Confusing methods on state with inheritance
Thinking methods only perform calculations
Believing methods handle external input only
2. Which of the following is the correct syntax for a method that changes an object's state in C#?
easy
A. public void UpdateName(string newName) { name = newName; }
B. void UpdateName(string newName) name = newName;
C. public UpdateName(string newName) { name = newName; }
D. public void UpdateName(string newName) => return name = newName;
Solution
Step 1: Check method declaration syntax
In C#, methods must specify access modifier, return type, name, and parameters inside parentheses, with body in braces.
Step 2: Verify the method body updates the state correctly
public void UpdateName(string newName) { name = newName; } correctly assigns newName to the field name inside braces.
Final Answer:
public void UpdateName(string newName) { name = newName; } -> Option A
Quick Check:
Correct method syntax = public void UpdateName(string newName) { name = newName; } [OK]
Hint: Remember method syntax: access + return type + name(params) { body } [OK]
Common Mistakes:
Missing braces around method body
Omitting return type
Using return with void methods incorrectly
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. 3
B. 1
C. 0
D. 2
Solution
Step 1: Trace the Increment method calls
Each call to Increment increases count by 1. Two calls increase count from 0 to 2.
Step 2: Check the GetCount method output
GetCount returns the current count, which is 2 after two increments.
Final Answer:
2 -> Option D
Quick Check:
2 increments = count 2 [OK]
Hint: Count increments twice, so output is 2 [OK]
Common Mistakes:
Forgetting that count starts at 0
Assuming Increment adds more than 1
Confusing method names or outputs
4. Identify the error in this method that tries to update an object's state:
public void SetAge(int age) {
int age = age;
}
medium
A. The method redeclares 'age' variable causing a conflict
B. The method is missing a return statement
C. The method should be static to update state
D. The method should not have parameters
Solution
Step 1: Analyze variable declarations inside the method
The method declares a new local variable 'int age', which conflicts with the parameter 'age'.
Step 2: Understand how to update the object's field
To update the object's state, assign the parameter to the field, e.g., this.age = age; without redeclaring.
Final Answer:
The method redeclares 'age' variable causing a conflict -> Option A
Quick Check:
Variable redeclaration error = The method redeclares 'age' variable causing a conflict [OK]
Thinking missing return causes error in void method
Assuming static needed to update instance state
Believing parameters should be removed
5. You have a class BankAccount with a private field balance. You want to add a method Withdraw that subtracts an amount only if there is enough balance. Which method implementation correctly operates on the state safely?
hard
A. public decimal Withdraw(decimal amount) { return balance - amount; }
B. public void Withdraw(decimal amount) { balance -= amount; }
C. public void Withdraw(decimal amount) { if (amount <= balance) balance -= amount; else Console.WriteLine("Insufficient funds"); }
D. public void Withdraw(decimal amount) { if (amount < 0) balance += amount; }
Solution
Step 1: Check for safe state update conditions
Method should only subtract amount if balance is enough to avoid negative balance.
Step 2: Verify method behavior on insufficient funds
public void Withdraw(decimal amount) { if (amount <= balance) balance -= amount; else Console.WriteLine("Insufficient funds"); } checks amount <= balance and prints a message if not enough, preventing invalid state.
Final Answer:
public void Withdraw(decimal amount) { if (amount <= balance) balance -= amount; else Console.WriteLine("Insufficient funds"); } -> Option C
Quick Check:
Safe state update with condition = public void Withdraw(decimal amount) { if (amount <= balance) balance -= amount; else Console.WriteLine("Insufficient funds"); } [OK]
Hint: Check balance before subtracting to avoid negative state [OK]
Common Mistakes:
Subtracting without checking balance
Returning new value without updating state
Adding amount when negative instead of subtracting