Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I explicitly cast an int to a string?

Tags:

c#

casting

If I try to do this it doesn't work:

static void Main(string[] args)
{
    int a = 5000;
    Console.WriteLine((string)a);
}

But somehow this works fine:

static void Main(string[] args)
{
    int a = 5000;
    Console.WriteLine(a + "");
}

Why is that? Is it because the first is trying to change the base type and the second just appends the value to the string?

like image 850
MattBH Avatar asked Sep 06 '11 13:09

MattBH


People also ask

Can we type cast int to string?

We can convert int to String in java using String. valueOf() and Integer. toString() methods. Alternatively, we can use String.

Can you cast an int to a string C#?

Converting int to string in C# is used to convert non-decimal numbers to string character. This can be done by using int to string conversion, int to string with Int32. ToString(), int to string with string concatenation, int to string with StringBuilder, int to string with Convert.


3 Answers

int cannot be cast to string (1), but there is an operator + that accepts int as left-hand argument and string as right-hand argument (2). This operator converts the int to string and concatenates the two strings.

A better approach would probably be to just use Console.WriteLine(a); which would call a.ToString() for you.

like image 168
larsmoa Avatar answered Oct 26 '22 20:10

larsmoa


So you are getting a compile time error right? The problem is is that int does not explicitly cast to string.

So

(string)a

is not valid code but

a + ""

mean that the code will work because it basically get translated to

a.ToString() + ""

So the int gets converted into a string value

like image 34
musefan Avatar answered Oct 26 '22 19:10

musefan


You should use:

static void Main(string[] args)
{
    int a = 5000;
    Console.WriteLine(a);
}

that implicitly calls a.ToString()

like image 24
Marco Avatar answered Oct 26 '22 19:10

Marco