Question

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).

Was it helpful?

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).

OTHER TIPS

Well, string and object - both of them are reference types. However, object is a root type for all .NET types.

When you use such syntax as (string)i, you are trying to use explicit conversion beetween types. But this conversion type requires string class to know about all possible argument types.

So we have .ToString() method, which can be overriden in any class, and its return value is used as a string represenation of any object.

string s = i and string s = (string)i does not work

because I is not a string, and type CASTING is a CAST of the type, not a conversion. It only works if i contains a string or a subclass of string (which is not possible for strings, but may be for other classes).

whats the difference in using (string)i, i.ToString(), and Convert.ToString(i).

  • (string) i: cast i to a string, must be assignable.

  • i.ToString(): calls the ToSstring method, which is defiend on System.object, thus available on ALL classes and structs - but returns no sensible content if not overwritten.

  • Convert.ToString(i): coonverts i to a string. THis includes calling a converter which likely just calls ToString on this rare case.

At the end, casting is not aconversion. for (string) i to work i HAS TO BE A STRING, while convert tries to MAKE it a string.

You can specify implicit and explicit conversions in .net, the reason that string s = i fails is that there is no built in cast operation for an integer to a string.

see this MSDN article on casting for further information

string s= i does not work because the types don't match, int won't go into a string.

string s=(string)i does not work because it cannot asume which type conversion is to be used (i.e which base)

something like s = ""+i would work on the other hand as it would asume base 10 conversion.

so i want to know why string s = i and string s = (string)i does not work

The short answer is that there is no implict (first example above) nor explicit (second example above) cast from int to string defined. Slightly longer answer; when authoring the struct Int32 in C# no casting behaviour was programmed to enable the developer to automagically cast from an int to a string

whats the difference in using (string)i, i.ToString(), and Convert.ToString(i)

Well, the first doesn;t work as you said, and as ive explained above. The second calls the ToString method on the struct Int32, which returns (as the name implies) a string representation of the object. It should be noted that this is a brand new string, not in any way related to the original value. The third example Convert.ToString will, under the hood, call whatever the most appropriate way to turn the parameter passed in to a string - most likely just calls the ToString method - so pretty much identical to example 2.

ToString() method is override by each referance which is vitual method in the object class. string calss override that method and provide string value out of this.

The default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.

 Object obj = new Object();
      Console.WriteLine(obj.ToString());

// The example displays the following output:
//      System.Object

this behavior is inherited by reference types that do not override the ToString method.

Typecasting in C# only works along the lines of class inheritance. Object is the root of all types in C# and therefore all values can be typecast to it.

string and int do not share the same branch of inheritance and so cannot be directly cast from one to the other.

Convert.ToString() is a method designed to convert an integer to a string - there's no typecasting going on, it's just executing a method designed to convert an integer to a string representation.

i.ToString() performs the equivalent functionality to Convert.ToString(), except that i.ToString() has overloads which allow greater flexibility on the representation of the number in string format.

One last note, exceptions to the typecasting rules can be included by the developer by using a public static explicit operator method which permits the developer to convert one value to another as they see fit.

First thing to note is that every class derives from object.

Casting int to object is using an Int32.

Casting string to object is using a String.

There is no implicit cast from an integer to a string because they are in different parts of the class hierarchy - one does not in any way relate to another. However because string is used so often for output object (and therefore all its children) have a ToString() method for convenience.

However Convert is written specifically to be able to convert from one type to another, for example Convert.ToBool(x) can parse "true" or "false" to boolean, and as you have shown it can convert an integer to a string - again this is really a convenience that probably just calls Int32.ToString() under the hood.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top