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?
We can convert int to String in java using String. valueOf() and Integer. toString() methods. Alternatively, we can use String.
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.
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 string
s.
A better approach would probably be to just use Console.WriteLine(a);
which would call a.ToString()
for you.
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
You should use:
static void Main(string[] args)
{
int a = 5000;
Console.WriteLine(a);
}
that implicitly calls a.ToString()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With