Consider the following code:
void Handler(object o, EventArgs e)
{
// I swear o is a string
string s = (string)o; // 1
//-OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3
}
What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?
Best Answer
Throws InvalidCastException if
o
is not astring
. Otherwise, assignso
tos
, even ifo
isnull
.Assigns
null
tos
ifo
is not astring
or ifo
isnull
. For this reason, you cannot use it with value types (the operator could never returnnull
in that case). Otherwise, assignso
tos
.Causes a NullReferenceException if
o
isnull
. Assigns whatevero.ToString()
returns tos
, no matter what typeo
is.Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).
3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.