Sunday 11 October, 2009

Difference between obj.ToString() vs Convert.ToString(obj) vs (string)obj vs obj as string

obj.ToString()


.ToString() can be called from any object. It returns a string that represents the current Object. ToString() is a method of object, and it will always work on a non-null reference. For example:

object str = "test string";
string newTestString = str.ToString();

str.ToString() will return "test string" as string .But

object str = null;
string newTestString = str.ToString();


Will throw the exception:“Object reference not set to an instance of an object.”
The above exception came because str is null we can not perform any operation on any object that has null reference.

Convert.ToString(obj) :

Convert.ToString(obj) means we are calling a method and passing obj as argument.Internally it will call ToString(object value) method and then ToString(object value, IFormatProvider provider) method is called.

(string)obj :
First it should be clear that it is a cast operation, not a function (or method) call. We should use this if we are sure the object we are passing is of type string or it has an implicit or explicit operator that can convert the object to a string. This will return null if the object itself is null . See examples.

object str = "test string";
string newTestString = (string)str;

(string)str will return "test string" as string.But you cant do tht for Int.See below example:

object i = 2;
string str = (string)i;

The above code will throw this error:
Unable to cast object of type 'System.Int32' to type 'System.String'.Cannot cast expression of type int to string
Int doesn't have an explicit operator to string.When casting a number to a string, there is a "loss" in data. A string cannot perform mathematical operations, and it can't do number related things.

obj as string :
It is safe cast operation. It is similar like (string)obj but instead of throwing an exception it will return null if cast operation fails. For example:

object i = 2;
string str = i as string;

str will return null.

No comments:

Post a Comment