C#.NET — Set a constant value 3.14 for pi so it cannot be modified later: choose the correct construct.

Difficulty: Easy

Correct Answer: const float pi = 3.14F;

Explanation:


Introduction / Context:
Constants in C# are compile-time values that cannot change after compilation. This question asks which syntax properly defines an immutable numeric constant.



Given Data / Assumptions:

  • Desired value: 3.14 (float literal → use suffix F).
  • Requirement: cannot be modified later.


Concept / Approach:
Use const for compile-time constants. A const must be assigned at declaration. #define in C# only defines a conditional compilation symbol, not a numeric macro as in C/C++.



Step-by-Step Solution:

Option C: const float pi = 3.14F; — Correct. Immutable at compile-time and accessible where in scope. Option A: float pi = 3.14F; — Mutable variable, not a constant. Option B: #define pi 3.14F; — Invalid in C# for numeric macros; #define only declares symbols. Option D: Split const declaration and assignment — illegal; const must be assigned inline. Option E: Assignment with no declaration — invalid.


Verification / Alternative check:
Attempting to reassign pi when declared const produces a compile-time error, proving immutability.



Why Other Options Are Wrong:
They either define mutable data or use invalid/unsupported syntax.



Common Pitfalls:
Confusing const with readonly (readonly allows assignment in constructor at run time; const is compile-time).



Final Answer:
const float pi = 3.14F;

More Questions from Datatypes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion