Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (string)int32 always throw: Cannot convert type 'int' to 'string'

Tags:

c#

compilation

Why does (string)int32 always throw: Cannot convert type 'int' to 'string'

public class Foo
    {   
        private int FooID;
        public Foo()
        {
            FooID = 4;
            string s = (string)FooID; //throws compile error
            string sss = FooID.ToString(); //no compile error
        }
    }
like image 851
tanbuckeye Avatar asked Nov 26 '22 20:11

tanbuckeye


2 Answers

Because there is no type conversion defined from Int32 to string. That's what the ToString method is for.

like image 88
mqp Avatar answered Dec 16 '22 03:12

mqp


If you did this:

string s = (string)70;

What would you expect to be in s?

A. "70" the number written the way humans would read it.
B. "+70" the number written with a positive indicator in front.
C. "F" the character represented by ASCII code 70.
D. "\x00\x00\x00F" the four bytes of an int each separately converted to their ASCII representation.
E. "\x0000F" the int split into two sets of two bytes each representing a Unicode character.
F. "1000110" the binary representation for 70.
G. "$70" the integer converted to a currency
H. Something else.

The compiler can't tell so it makes you do it the long way.

There are two "long ways". The first is to use one of the the Convert.ToString() overloads something like this:

string s = Convert.ToString(-70, 10);

This means that it will convert the number to a string using base 10 notation. If the number is negative it displays a "-" at the start, otherwise it just shows the number. However if you convert to Binary, Octal or Hexadecimal, negative numbers are displayed in twos complement so Convert.ToString(-7, 16) becomes "ffffffba".

The other "long way" is to use ToString with a string formatter like this:

string s2 = 70.ToString("D");

The D is a formatter code and tells the ToString method how to convert to a string. Some of the interesting codes are listed below:

"D" Decimal format which is digits 0-9 with a "-" at the start if required. E.g. -70 becomes "-70".
"D8" I've shown 8 but could be any number. The same as decimal, but it pads with zeros to the required length. E.g. -70 becomes "-00000070".
"N" Thousand separators are inserted and ".00" is added at the end. E.g. -1000 becomes "-1,000.00".
"C" A currency symbol is added at the start after the "-" then it is the same as "N". E.g. Using en-Gb culture -1000 becomes "-£1,000.00".
"X" Hexadecimal format. E.g. -70 becomes "46".

Note: These formats are dependent upon the current culture settings so if you are using en-Us you will get a "$" instead of a "£" when using format code "C".

For more information on format codes see MSDN - Standard Numeric Format Strings.

like image 43
Martin Brown Avatar answered Dec 16 '22 04:12

Martin Brown