Challenge - 5 Problems
Constant Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of constant and readonly fields
What is the output of this C# program?
C Sharp (C#)
using System; class Test { public const int ConstValue = 10; public readonly int ReadonlyValue; public Test(int val) { ReadonlyValue = val; } public void PrintValues() { Console.WriteLine($"ConstValue = {ConstValue}, ReadonlyValue = {ReadonlyValue}"); } } class Program { static void Main() { Test t = new Test(20); t.PrintValues(); } }
Attempts:
2 left
💡 Hint
Remember that const values are fixed at compile time and readonly values can be set in the constructor.
✗ Incorrect
ConstValue is a constant set to 10 and cannot change. ReadonlyValue is set in the constructor to 20, so it prints 20.
❓ Predict Output
intermediate2:00remaining
Readonly field modification attempt
What happens when you try to compile and run this code?
C Sharp (C#)
class Sample { public readonly int ReadonlyField = 5; public void Change() { ReadonlyField = 10; } } class Program { static void Main() { Sample s = new Sample(); s.Change(); System.Console.WriteLine(s.ReadonlyField); } }
Attempts:
2 left
💡 Hint
Readonly fields can only be assigned in declaration or constructor.
✗ Incorrect
Assigning to a readonly field outside the constructor or declaration causes a compile-time error.
🧠 Conceptual
advanced2:00remaining
Difference between const and readonly
Which statement correctly describes the difference between const and readonly fields in C#?
Attempts:
2 left
💡 Hint
Think about when the values are assigned and if they can change after that.
✗ Incorrect
const fields are fixed at compile time and cannot be changed. readonly fields can be assigned once at runtime, typically in the constructor.
❓ Predict Output
advanced2:00remaining
Readonly field with static constructor
What is the output of this program?
C Sharp (C#)
using System; class Example { public static readonly int Value; static Example() { Value = 42; } } class Program { static void Main() { Console.WriteLine(Example.Value); } }
Attempts:
2 left
💡 Hint
Static readonly fields can be assigned in static constructors.
✗ Incorrect
Static readonly fields can be assigned in static constructors and keep that value for the program lifetime.
❓ Predict Output
expert2:00remaining
Constant expression evaluation
What is the output of this program?
C Sharp (C#)
using System; class ConstTest { public const int A = 5; public const int B = A * 2; public const int C = B + 3; } class Program { static void Main() { Console.WriteLine(ConstTest.C); } }
Attempts:
2 left
💡 Hint
Const expressions can use other const fields in their definitions.
✗ Incorrect
Const fields can be used in expressions to define other const fields. Here C = (5*2)+3 = 13.