Search code examples
c#boxingunboxing

type casting in c#.net


i want to know typecasting in c# .net, i have below lines of code.

int i=4
object o = i // This works properly without any typecasting becausing boxing takes place automatically
string s= i // This does not work, even when the string is also reference type?
string s=(string)i //This also does not work even if i try to typecast the int to string.
string s= Convert.ToString(i); // this works.

so i want to know why string s = i and string s = (string)i does not work and whats the difference in using (string)i, i.ToString(), and Convert.ToString(i).


Solution

  • When it comes to boxing and unboxing, types have explicit and implicit casting. So, in some circumstances, it is easy enough for the runtime to allow for implicit conversion between two supported types, say an Int32 to a Double. However, there is no implicit or explicit conversion between an integer and a string, because obviously, a string is not an integer (despite the fact that a string can contain characters for an integer).

    string s = i; // attempt at implicit cast from Int32 to String, error
    object o = i; // all types inherit from Object, so you may implicitly or explicitly cast from Int32 to Object.
    s = (string)i; // attempt at explicit cast from Int32 to string, error
    s = i.ToString(); // conversion
    s = Convert.ToString(i); // conversion
    

    That's where Convert comes to play. Convert contains support for attempting to convert known primitives (and types supporting IConvertable) to another. So, ToString or Convert.ToString would be the preferred methods (ToString and Convert.ToString are virtually synonymous, except that ToString gives you some formatting options).