Difficulty: Easy
Correct Answer: s = Convert.ToString(f);
Explanation:
Introduction / Context:
Converting numeric types to strings is routine in C#.NET. The question presents several code snippets and asks which are valid for converting a Single
(alias float
) into a String
.
Given Data / Assumptions:
Single f = 9.8f;
then assign a string
variable s
.
Concept / Approach:
In C#, use Convert.ToString
or the instance ToString()
method. Direct casting from float
to string
is illegal, and VB-specific functions like CString
or Clnt
do not exist in C#.
Step-by-Step Solution:
s = Convert.ToString(f);
→ uses framework converter.Valid: s = f.ToString();
→ instance method on value type.Invalid: (String)(f)
→ no direct cast defined.Invalid: Clnt
and CString
→ VB-style; not C# identifiers.
Verification / Alternative check:
Try formatting: f.ToString("F2")
for 2 decimal places, demonstrating rich formatting support.
Why Other Options Are Wrong:
They are either syntactically invalid in C# or rely on non-existent conversion helpers.
Common Pitfalls:
Assuming a C-style cast will work for disparate types like float
to string
.
Final Answer:
s = Convert.ToString(f); (also acceptable: s = f.ToString();)
Discussion & Comments