Microsoft Certified Solutions Developer (MCSD) Practice Test 2025 – Complete Exam Prep

Question: 1 / 400

What is the key difference between readonly and const in C#?

Readonly can be assigned multiple times

Const can only be assigned at definition

Readonly allows setting in a constructor, const does not

The distinction between readonly and const in C# primarily revolves around how and when these keywords can be assigned values. The correct choice highlights that readonly fields can be assigned values within a constructor, whereas const fields must be assigned a value at the time of their declaration.

When a variable is declared as const, it is a compile-time constant, which means its value is fixed and cannot be changed after that initial assignment. This also means that const values are evaluated at compile time, and any attempt to assign a new value to them later in the code will result in a compilation error.

In contrast, a readonly field can be assigned either at its declaration or within a constructor of its containing class. This flexibility allows readonly fields to be set based on parameters passed to the constructor or determined at runtime, which is particularly useful for situations where the value might need to depend on circumstances that are only known when an object is instantiated.

While readonly fields can indeed be static, allowing them to be shared across all instances of a class, const fields are inherently static by default but cannot be assigned a value outside of their declaration. The key takeaway is the timing and location of value assignment, as outlined in the correct answer.

Get further explanation with Examzify DeepDiveBeta

Readonly can be static while const cannot

Next Question

Report this question

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy