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

Readonly structs in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Readonly Structs Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of readonly struct method call
What is the output of this C# code using a readonly struct?
C Sharp (C#)
readonly struct Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public int Sum() => X + Y;
}

class Program
{
    static void Main()
    {
        Point p = new Point(3, 4);
        System.Console.WriteLine(p.Sum());
    }
}
A7
B0
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Think about what the Sum method returns and how readonly structs behave.
❓ Predict Output
intermediate
2:00remaining
Effect of modifying field in readonly struct
What happens when you try to modify a field inside a readonly struct method?
C Sharp (C#)
readonly struct Counter
{
    private int count;

    public void Increment()
    {
        count++;
    }

    public int GetCount() => count;
}

class Program
{
    static void Main()
    {
        Counter c = new Counter();
        c.Increment();
        System.Console.WriteLine(c.GetCount());
    }
}
AOutput: 0
BOutput: 1
CCompilation error: cannot modify field in readonly struct
DRuntime exception
Attempts:
2 left
💡 Hint
Readonly structs prevent modification of fields inside instance methods.
🔧 Debug
advanced
2:00remaining
Why does this readonly struct code fail to compile?
Identify the reason for the compilation error in this readonly struct code.
C Sharp (C#)
readonly struct Rectangle
{
    public int Width { get; set; }
    public int Height { get; set; }

    public int Area() => Width * Height;
}

class Program
{
    static void Main()
    {
        Rectangle r = new Rectangle { Width = 5, Height = 10 };
        System.Console.WriteLine(r.Area());
    }
}
AArea method cannot access properties in readonly struct
BNo compilation error
CCannot initialize readonly struct with object initializer
DReadonly structs cannot have set accessors in properties
Attempts:
2 left
💡 Hint
Think about what readonly means for property setters in structs.
📝 Syntax
advanced
2:00remaining
Which option correctly declares a readonly struct with an immutable field?
Choose the correct syntax to declare a readonly struct with an immutable field 'Id' of type int.
Areadonly struct User { public readonly int Id; public User(int id) { Id = id; } }
Breadonly struct User { public int Id; public User(int id) { Id = id; } }
Creadonly struct User { int Id; public User(int id) { Id = id; } }
Dstruct User { readonly int Id; public User(int id) { Id = id; } }
Attempts:
2 left
💡 Hint
Remember to use 'public readonly' for immutable fields in readonly structs.
🚀 Application
expert
2:00remaining
How many items are in the resulting list after processing readonly structs?
Given this code, how many elements does the list 'areas' contain after execution?
C Sharp (C#)
readonly struct Square
{
    public int Side { get; }
    public Square(int side) => Side = side;
    public int Area() => Side * Side;
}

class Program
{
    static void Main()
    {
        var squares = new Square[] { new(2), new(3), new(4) };
        var areas = new System.Collections.Generic.List<int>();
        foreach (var sq in squares)
        {
            areas.Add(sq.Area());
        }
        System.Console.WriteLine(areas.Count);
    }
}
A0
B3
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Count how many squares are in the array and how many times the loop runs.

Practice

(1/5)
1.

What is the main purpose of declaring a struct as readonly in C#?

easy
A. To allow inheritance from the struct
B. To make the struct mutable
C. To enable dynamic resizing of the struct
D. To prevent modification of its fields after creation

Solution

  1. Step 1: Understand what readonly means for structs

    A readonly struct means its fields cannot be changed after the struct is created.
  2. Step 2: Compare options with this meaning

    Only To prevent modification of its fields after creation matches this behavior by preventing modification after creation.
  3. Final Answer:

    To prevent modification of its fields after creation -> Option D
  4. Quick Check:

    Readonly struct = Immutable fields [OK]
Hint: Readonly structs make data unchangeable after creation [OK]
Common Mistakes:
  • Thinking readonly allows inheritance
  • Confusing readonly with mutable structs
  • Assuming readonly structs can resize dynamically
2.

Which of the following is the correct way to declare a readonly struct in C#?

?
easy
A. readonly struct Point { public int X; public int Y; }
B. struct readonly Point { public int X; public int Y; }
C. struct Point readonly { public int X; public int Y; }
D. readonly Point struct { public int X; public int Y; }

Solution

  1. Step 1: Recall correct syntax for readonly structs

    The keyword readonly comes before struct in the declaration.
  2. Step 2: Check each option's keyword order

    Only readonly struct Point { public int X; public int Y; } places readonly before struct correctly.
  3. Final Answer:

    readonly struct Point { public int X; public int Y; } -> Option A
  4. Quick Check:

    Keyword order: readonly struct [OK]
Hint: Put 'readonly' before 'struct' keyword [OK]
Common Mistakes:
  • Placing readonly after struct
  • Mixing order of keywords
  • Using readonly as a suffix
3.

What will be the output of the following C# code?

readonly struct Point
{
    public int X { get; }
    public int Y { get; }
    public Point(int x, int y) { X = x; Y = y; }
}

var p = new Point(3, 4);
Console.WriteLine($"X: {p.X}, Y: {p.Y}");
medium
A. X: 3, Y: 4
B. X: 0, Y: 0
C. Compilation error due to readonly struct
D. Runtime error when accessing properties

Solution

  1. Step 1: Understand readonly struct with get-only properties

    The struct has get-only properties set in the constructor, which is allowed.
  2. Step 2: Check the constructor and output

    The constructor sets X=3 and Y=4, so printing them outputs "X: 3, Y: 4".
  3. Final Answer:

    X: 3, Y: 4 -> Option A
  4. Quick Check:

    Constructor sets values correctly [OK]
Hint: Readonly structs allow get-only properties set in constructor [OK]
Common Mistakes:
  • Assuming readonly structs cannot have properties
  • Thinking constructor cannot set properties
  • Expecting runtime errors accessing properties
4.

Identify the error in this code snippet using a readonly struct:

readonly struct Rectangle
{
    public int Width;
    public int Height;

    public void Resize(int w, int h)
    {
        Width = w;
        Height = h;
    }
}
medium
A. Fields must be properties in readonly structs
B. Missing constructor for readonly struct
C. Cannot assign to fields inside a method of a readonly struct
D. Readonly structs cannot have methods

Solution

  1. Step 1: Understand mutability rules in readonly structs

    Readonly structs cannot modify their fields inside instance methods.
  2. Step 2: Analyze the Resize method

    Resize tries to assign new values to Width and Height fields, which is not allowed.
  3. Final Answer:

    Cannot assign to fields inside a method of a readonly struct -> Option C
  4. Quick Check:

    Readonly struct fields are immutable in methods [OK]
Hint: Readonly struct methods cannot change fields [OK]
Common Mistakes:
  • Thinking methods can modify fields in readonly structs
  • Assuming missing constructor causes error
  • Believing readonly structs cannot have any methods
5.

You want to create a readonly struct Circle that stores a radius and calculates area. Which of these implementations is correct and efficient?

?
hard
A. readonly struct Circle { public double Radius; public void SetRadius(double r) { Radius = r; } }
B. readonly struct Circle { public double Radius { get; } public Circle(double r) => Radius = r; public double Area => Math.PI * Radius * Radius; }
C. struct Circle { public double Radius; public double Area => Math.PI * Radius * Radius; }
D. readonly struct Circle { public double Radius { get; set; } public double Area() => Math.PI * Radius * Radius; }

Solution

  1. Step 1: Check readonly struct with immutable radius

    readonly struct Circle { public double Radius { get; } public Circle(double r) => Radius = r; public double Area => Math.PI * Radius * Radius; } uses a readonly struct with a get-only property set in constructor, which is correct.
  2. Step 2: Verify area calculation and mutability

    Area is a property calculated from Radius, no setters modify Radius, ensuring immutability and efficiency.
  3. Final Answer:

    readonly struct Circle { public double Radius { get; } public Circle(double r) => Radius = r; public double Area => Math.PI * Radius * Radius; } -> Option B
  4. Quick Check:

    Immutable radius with calculated area [OK]
Hint: Use get-only property and constructor for readonly struct fields [OK]
Common Mistakes:
  • Trying to set fields in readonly struct after creation
  • Using mutable fields in readonly structs
  • Adding setters that break immutability
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard