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

Get and set accessors 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
🎖️
Accessor 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 C# code using get and set accessors?

Consider the following C# class with a property using get and set accessors. What will be printed when the program runs?

C Sharp (C#)
class Person {
    private string name;
    public string Name {
        get { return name; }
        set { name = value.ToUpper(); }
    }
}

class Program {
    static void Main() {
        Person p = new Person();
        p.Name = "alice";
        System.Console.WriteLine(p.Name);
    }
}
Anull
Balice
CAlice
DALICE
Attempts:
2 left
💡 Hint

Look at how the set accessor modifies the value before storing it.

Predict Output
intermediate
2:00remaining
What value does the property return after setting it?

Given this C# code, what will be the output?

C Sharp (C#)
class Counter {
    private int count;
    public int Count {
        get { return count; }
        set {
            if (value >= 0) count = value;
        }
    }
}

class Program {
    static void Main() {
        Counter c = new Counter();
        c.Count = -5;
        System.Console.WriteLine(c.Count);
    }
}
A-5
B0
CThrows an exception
DUninitialized value
Attempts:
2 left
💡 Hint

Check what happens when the set accessor receives a negative value.

🔧 Debug
advanced
2:00remaining
Why does this property cause a stack overflow error?

Examine the following C# property. Why does it cause a runtime error?

C Sharp (C#)
class Sample {
    private int number;
    public int Number {
        get { return Number; }
        set { Number = value; }
    }
}
AThe get and set accessors recursively call themselves causing a stack overflow.
BThe private field 'number' is not initialized causing a null reference exception.
CThe property is missing a semicolon causing a syntax error.
DThe property uses an invalid data type causing a compile error.
Attempts:
2 left
💡 Hint

Look at what the get and set accessors are returning and assigning.

📝 Syntax
advanced
2:00remaining
Which option correctly defines a read-only property with a private set accessor?

Choose the correct C# property syntax that allows reading the value publicly but only setting it privately within the class.

Apublic int Age { get private; set; }
Bpublic int Age { private get; set; }
Cpublic int Age { get; private set; }
Dpublic int Age { get; set; private }
Attempts:
2 left
💡 Hint

Remember the correct order and syntax for access modifiers on accessors.

🚀 Application
expert
3:00remaining
How many items are in the dictionary after this code runs?

Analyze this C# code using a property with get and set accessors that modify a dictionary. How many key-value pairs does the dictionary contain after execution?

C Sharp (C#)
class DataStore {
    public Dictionary<string, int> data = new();
    public int this[string key] {
        get => data.ContainsKey(key) ? data[key] : -1;
        set {
            if (value >= 0) data[key] = value;
            else if (data.ContainsKey(key)) data.Remove(key);
        }
    }
}

class Program {
    static void Main() {
        DataStore store = new DataStore();
        store["a"] = 10;
        store["b"] = 20;
        store["a"] = -5;
        store["c"] = 0;
        store["b"] = -1;
        System.Console.WriteLine(store.data.Count);
    }
}
A1
B2
C3
D0
Attempts:
2 left
💡 Hint

Track how the set accessor adds, updates, or removes keys based on the value.

Practice

(1/5)
1. What is the main purpose of get and set accessors in a C# class?
easy
A. To handle exceptions automatically
B. To define methods that perform calculations
C. To create variables inside a class
D. To control how a property value is read and changed

Solution

  1. Step 1: Understand the role of accessors

    Get and set accessors are used to read and write property values in a controlled way.
  2. Step 2: Differentiate from other class members

    They are not methods or variables themselves but control access to data.
  3. Final Answer:

    To control how a property value is read and changed -> Option D
  4. Quick Check:

    Get/set control property access = A [OK]
Hint: Get/set control property reading and writing [OK]
Common Mistakes:
  • Confusing accessors with methods
  • Thinking they create variables
  • Assuming they handle exceptions automatically
2. Which of the following is the correct syntax for an auto-implemented property with get and set accessors in C#?
easy
A. public int Age { get() set(); }
B. public int Age() { get; set; }
C. public int Age { get; set; }
D. public int Age get; set;

Solution

  1. Step 1: Identify correct property syntax

    Auto-properties use curly braces with get and set accessors separated by semicolons.
  2. Step 2: Check each option

    public int Age { get; set; } matches the correct syntax: public int Age { get; set; }
  3. Final Answer:

    public int Age { get; set; } -> Option C
  4. Quick Check:

    Auto-property syntax = C [OK]
Hint: Auto-properties use braces with get; set; inside [OK]
Common Mistakes:
  • Using parentheses instead of braces
  • Missing semicolons after get and set
  • Writing get and set without braces
3. What will be the output of the following C# code?
class Person {
  private string name;
  public string Name {
    get { return name; }
    set { name = value.ToUpper(); }
  }
}

var p = new Person();
p.Name = "alice";
Console.WriteLine(p.Name);
medium
A. alice
B. ALICE
C. Name
D. null

Solution

  1. Step 1: Analyze the set accessor behavior

    The set accessor converts the assigned value to uppercase before storing it in the private field.
  2. Step 2: Analyze the get accessor output

    The get accessor returns the stored uppercase string.
  3. Final Answer:

    ALICE -> Option B
  4. Quick Check:

    Set converts to uppercase, output = ALICE [OK]
Hint: Set modifies value before storing, get returns stored value [OK]
Common Mistakes:
  • Ignoring the ToUpper() call in set
  • Assuming original case is preserved
  • Confusing field and property names
4. Identify the error in this property definition:
public int Score {
  get { return score; }
  set score = value; }
}
medium
A. Incorrect set accessor syntax
B. Missing semicolon after return statement
C. Missing private field declaration
D. Property name should be lowercase

Solution

  1. Step 1: Check set accessor syntax

    The set accessor must use braces { } around its code block, but here it is missing the opening brace.
  2. Step 2: Confirm other parts

    The return statement has a semicolon, private field may be declared elsewhere, and property names are PascalCase by convention.
  3. Final Answer:

    Incorrect set accessor syntax -> Option A
  4. Quick Check:

    Set accessor needs braces = A [OK]
Hint: Set accessor must have braces around code block [OK]
Common Mistakes:
  • Omitting braces in set accessor
  • Confusing property and field names
  • Assuming property names must be lowercase
5. You want to create a property Age that only allows values between 0 and 120. Which implementation correctly enforces this using get and set accessors?
hard
A. private int age; public int Age { get { return age; } set { if (value >= 0 && value <= 120) age = value; } }
B. public int Age { get; set; } // No validation needed
C. private int age; public int Age { get { return age; } set { age = value; } }
D. private int age; public int Age { get { return age; } set { if (value > 0) age = value; } }

Solution

  1. Step 1: Check validation logic in set accessor

    private int age; public int Age { get { return age; } set { if (value >= 0 && value <= 120) age = value; } } checks if value is between 0 and 120 before assigning it to the private field.
  2. Step 2: Compare other options

    The auto-implemented property has no validation. The simple backing field assignment lacks checks. The partial validation only checks if value > 0, missing the upper limit.
  3. Final Answer:

    private int age; public int Age { get { return age; } set { if (value >= 0 && value <= 120) age = value; } } -> Option A
  4. Quick Check:

    Set accessor validates range 0-120 = B [OK]
Hint: Use if condition in set to validate value range [OK]
Common Mistakes:
  • Not validating upper limit
  • Assigning value without checks
  • Assuming auto-properties validate automatically