Type Conversions
Implicit Type Conversions
This happens automatically, without you writing any special syntax. The compiler does it for you because it's "safe" (no data is lost).
int myInt = 100;
double myDouble = myInt; // int -> double is chill
A double can represent every value an int can, so nothing is lost, and C# performs the conversion silently.
Explicit Type Conversions
Explicit conversions are required when a conversion could lose data or fail. Here, the compiler forces you to cast, so it's clear you understand the risk.
double myDouble = 9.78;
int myInt = (int)myDouble; // myInt = 9
For string ↔ number conversions specifically, casting syntax doesn't apply, and you have to use these instead:
int number = 35;
string text = number.ToString(); // number -> string
string input = "42";
int parsed = int.Parse(input); // string -> int
Note: the word
Parserefers to reading text, and inferring specific information (in this case anint)
+ and Operator Evaluation Order
When mixing string and numeric types with +, results depend on evaluation order (left to right), not necessarily any implicit/explicit conversion happening behind the scenes.
string output; // output is always of type string.
output = "Hello " + (35 + 42); // output: Hello 77
Console.WriteLine(output);
output = "Hello " + 35 + 52; // output: Hello 3552
Console.WriteLine(output);
output = 35 + 42 + " Hello"; // output: 77 Hello
Console.WriteLine(output);
Using .ToString() explicitly avoids relying on this evaluation-order behavior, and makes intent clear:
string output;
output = "Hello " + (35 + 42).ToString();
Console.WriteLine(output);
output = "Hello " + 35.ToString() + 52.ToString();
Console.WriteLine(output);
output = (35 + 42).ToString() + " Hello";
Console.WriteLine(output);