Using ToString method to format nullable numeric variables

J

J Miro

When I use ToString method to format the value of a nullable numeric
variable, I get "No overload for method 'ToString' takes '1' arguments"
error message. Example:



Int32? myNum = 12345;

Console.WriteLine(myNum.ToString("n0")); //error



But if I declare myNum as non-nullable (Int32 myNum = 12345;), then ToString
formats its value fine! Why does ToString method generate an error when used
against a nullable variable? I should mention that String.Format handles
formatting of nullable values fine.



Thanks,

Jay
 
M

Michael Nemtsev

Hello J,

because nullable int doesn't have overloaded ToString which specify the output
format

---
WBR, Michael Nemtsev [.NET/C# MVP].
My blog: http://spaces.live.com/laflour
Team blog: http://devkids.blogspot.com/

"The greatest danger for most of us is not that our aim is too high and we
miss it, but that it is too low and we reach it" (c) Michelangelo

JM> When I use ToString method to format the value of a nullable numeric
JM> variable, I get "No overload for method 'ToString' takes '1'
JM> arguments" error message. Example:
JM>
JM> Int32? myNum = 12345;
JM>
JM> Console.WriteLine(myNum.ToString("n0")); //error
JM>
JM> But if I declare myNum as non-nullable (Int32 myNum = 12345;), then
JM> ToString formats its value fine! Why does ToString method generate
JM> an error when used against a nullable variable? I should mention
JM> that String.Format handles formatting of nullable values fine.
JM>
JM> Thanks,
JM>
JM> Jay
JM>
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Int32? is just a short version of System.Nullable<T>. It has no relation to
the "real" Int32. As such the class Nullable<T> has no ToString() overload
that accept a single parameter.
 
J

J Miro

Thank you all for your prompt response. Alex's solution works great.



Thanks gain.

Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top