Consider the following C# class and code. What will be printed when the program runs?
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());
Remember each object has its own copy of instance fields.
Each Counter object has its own count. c1 increments twice, so its count is 2. c2 increments once, so its count is 1.
What will be the value of balance after running this code?
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);
Think about adding and subtracting from the starting balance.
Starting balance is 100. Deposit adds 50 (total 150). Withdraw subtracts 30 (total 120).
Look at this code. Why does the count field not increase after calling Increment?
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());
Check variable names inside the method and the class.
Inside Increment, a new local variable count is declared, hiding the instance field. Incrementing the local variable does not affect the instance field.
Which of the following options correctly declares an instance field name of type string and initializes it to "Alice"?
Instance fields are declared inside the class but outside methods, with optional access modifiers and initialization.
Option A declares and initializes the instance field correctly. Options A and C try to assign outside a method or constructor, which is invalid syntax. Option A lacks an access modifier but is valid only if inside a class (default is private in C# fields).
Given the class and code below, how many unique Person objects have different age values after execution?
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);
Remember that p3 and p1 refer to the same object, as do p5 and p2.
p1 and p3 are the same object with age 30.p2 and p5 are the same object with age 35.p4 is a different object with age 30.
Unique ages are 30 and 35 only.
Counting distinct ages in the list: 30, 35, and 30 again (duplicate). So unique count is 2.