Consider the following C# class and code snippet. What will be printed to the console?
public 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());
Think about how many times the Increment method is called before printing.
The Increment method increases the count field by 1 each time it is called. Since it is called twice, the count becomes 2.
Given the following C# code, what will be the output?
public class BankAccount { private decimal balance = 100m; public void Withdraw(decimal amount) { balance -= amount; } public decimal GetBalance() { return balance; } } var account = new BankAccount(); account.Withdraw(30m); Console.WriteLine(account.GetBalance());
Subtract the withdrawn amount from the initial balance.
The initial balance is 100. After withdrawing 30, the balance becomes 70.
Examine the code below. Why does calling Reset not change the value field?
public class Data { private int value = 10; public void Reset(int value) { value = 0; } public int GetValue() { return value; } } var d = new Data(); d.Reset(5); Console.WriteLine(d.GetValue());
Look at the parameter name and the field name. Are they the same?
The method parameter value hides the field value. Assigning value = 0 changes the parameter only, not the field. To fix, use this.value = 0;.
Which of the following method definitions correctly updates the count field in a C# class?
Remember that methods that change state usually have void return type and update the field directly.
Option D correctly increments the count field. Option D does not assign the incremented value. Option D returns a value but does not update the field. Option D tries to return a value in a void method, causing a syntax error.
Given the following C# class and code, how many times is the value field changed?
public class Tracker { private int value = 0; public void Update(int newValue) { if (newValue != value) { value = newValue; } } public int GetValue() => value; } var t = new Tracker(); t.Update(5); t.Update(5); t.Update(10); t.Update(10); t.Update(5); Console.WriteLine(t.GetValue());
Count only when the value field actually changes.
The Update method changes value only if the new value differs. The changes happen at calls with 5 (from 0), 10 (from 5), and 5 (from 10), totaling 3 changes.