Why (string) int32 always throws: it is not possible to convert the type 'int' to 'string'

Why (string) int32 always throws: 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
        }
    }
+3
source share
9 answers

Because there is no type conversion defined from Int32 to string. This is the ToString method for.

+37
source

If you have done this:

string s = (string)70;

What do you expect to be in s?

. "70" , . B. "+70" , .
C. "F" , ASCII- 70.
D. "\ x00\x00\x00F" int, ASCII.
E. "\ x0000F" int , Unicode.
F. "1000110" 70.
G. "$ 70" ,
H. - .

, .

" ". -, Convert.ToString() - :

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

, 10. , "-" , . Binary, Octal Hexadecimal, , Convert.ToString(-7, 16) "ffffffba".

" " - ToString :

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

D ToString, . :

"D" , 0-9 "-" , . . -70 "-70".
"D8" 8, . , , . . -70 "-00000070".
"N" ".00". . -1000 "-1,000.00".
"C" "-" , "N". . en-Gb- -1000 "- 1000,00".
"X" . . -70 "46".

. , , en-Us, "$" "£" "C".

. MSDN - .

+19

, (string)30, , " , , ( ) /".

"" . , .

:

int test1 = 34;
double test2 = (double)test1;

:

int test1 = 34;
string test2 = (string)test1;

, (IIRC) , , double . - , double int. int string.

() , .

.ToString() , , string.

+10

Int . Int32.ToString();. , , .

+5

: , ( , ) Convert . / .

, # (, ++), , , , , . ++ , , # , , . Convert , .

+5

# , int , (.ToString) .

+4

Int32 , # , .

, , int32 - / , - oh well string string/characters. , (, float to int, ). , , , , , , NO NO.

, , # , .ToString(), , , .ToString() , , .

, Int32 (, 32 ), - ( , ), / ..ToString() , .

+4

. ToString int. , .

...

int intMyInt=32;

string strMyString = intMyInt.ToString();
+1

VB.net is very good at casting from int to string ... it's actually also Java. Why does C # have problems with this? Sometimes in calculations it is necessary to use a numerical value, and then display the result in a string format. How else will you be able to display the result of the calculation in a TextBox?

The responses given here make no sense. There should be a way to make int as a string.

-1
source

Source: https://habr.com/ru/post/1702480/


All Articles