Bird
0
0

Given this class:

hard🚀 Application Q9 of 15
C Sharp (C#) - Classes and Objects
Given this class:
class Logger {
    private static List logs = new List();
    public void Log(string message) {
        logs.Add(message);
    }
    public static void PrintLogs() {
        foreach (var log in logs) {
            Console.WriteLine(log);
        }
    }
}

What is the best way to use this class to log messages from multiple objects and print all logs?
AUse static methods only; do not create Logger objects.
BCall PrintLogs() on each Logger object separately.
CCreate one Logger object and call Log and PrintLogs() on it only.
DCreate multiple Logger objects, call Log on each, then call Logger.PrintLogs() once.
Step-by-Step Solution
Solution:
  1. Step 1: Understand static list behavior

    The static 'logs' list is shared by all Logger instances, so all logs accumulate there.
  2. Step 2: Use multiple objects to log

    Multiple Logger objects can add messages to the shared list via instance method Log.
  3. Step 3: Print all logs once

    Calling static PrintLogs() once prints all accumulated messages.
  4. Final Answer:

    Create multiple Logger objects, call Log on each, then call Logger.PrintLogs() once. -> Option D
  5. Quick Check:

    Static list shared; instance methods add logs [OK]
Quick Trick: Static list shared; instance methods add entries [OK]
Common Mistakes:
MISTAKES
  • Calling PrintLogs() on instances instead of class
  • Using only one Logger object for all logs
  • Trying to use static methods only without objects

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes