Microsoft Certified Solutions Developer (MCSD) Certification Practice Test

Disable ads (and more) with a membership for a one time $2.99 payment

Prepare for the Microsoft Certified Solutions Developer (MCSD) Certification Exam. Practice with flashcards and multiple choice questions. Master each topic with hints and insights. Achieve your certification goals!

Each practice test/flash card set has 50 randomly selected questions from a bank of over 500. You'll get a new set of questions each time!

Practice this question and more.


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

  1. Readonly can be assigned multiple times

  2. Const can only be assigned at definition

  3. Readonly allows setting in a constructor, const does not

  4. Readonly can be static while const cannot

The correct answer is: 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.