C#.NET — Predict output with overload resolution and double formatting. Consider: namespace CuriousTabConsoleApplication { class SampleProgram { static void Main(string[] args) { int i = 10; double d = 34.340; fun(i); fun(d); } static void fun(double d) { Console.WriteLine(d + " "); } } } What will be printed?

Difficulty: Medium

Correct Answer: 10 34.34

Explanation:


Introduction / Context:
This program tests overload resolution (int to double conversion) and how doubles are formatted when concatenated with a string in Console.WriteLine.


Given Data / Assumptions:

  • Only one overload exists: fun(double d).
  • Main calls fun(i) where i is int and fun(d) where d is double.
  • The method writes Console.WriteLine(d + " ").


Concept / Approach:
An int is implicitly converted to double to match the fun(double) signature. In the expression d + " ", the double is converted to its default string representation (culture-dependent general format “G”), then concatenated with a single trailing space, and finally written with a newline by WriteLine.


Step-by-Step Solution:

Call fun(i): i = 10 becomes 10.0 as a double. String concatenation produces "10 " (no trailing decimal digits in default formatting for an exact integer double). Call fun(d): d = 34.340 formats as "34.34" in default “G” formatting because trailing zeros are typically omitted. Thus the two lines are "10 " then "34.34 " (spaces included); considering options without spaces, this corresponds to “10 34.34”.


Verification / Alternative check:
Replacing WriteLine(d + " ") with WriteLine("{0} ", d) yields the same text. Using ToString("F6") would produce six fixed decimals (not used here).


Why Other Options Are Wrong:

  • A shows six fixed decimals — not used here.
  • B drops the fractional part of 34.340.
  • C keeps three decimals including a trailing zero — not default formatting here.
  • E is blank and not applicable.


Common Pitfalls:
Expecting WriteLine to preserve trailing zeros without an explicit format string; confusing numeric formatting with basic concatenation behavior.


Final Answer:
10 34.34

Discussion & Comments

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