It really depends on whether you know if o
is a string and what you want to do with it. If your comment means that o
really really is a string, I'd prefer the straight (string)o
cast - it's unlikely to fail.
The biggest advantage of using the straight cast is that when it fails, you get an InvalidCastException, which tells you pretty much what went wrong.
With the as
operator, if o
isn't a string, s
is set to null
, which is handy if you're unsure and want to test s
:
string s = o as string;
if ( s == null )
{
// well that's not good!
gotoPlanB();
}
However, if you don't perform that test, you'll use s
later and have a NullReferenceException thrown. These tend to be more common and a lot harder to track down once they happens out in the wild, as nearly every line dereferences a variable and may throw one. On the other hand, if you're trying to cast to a value type (any primitive, or structs such as DateTime), you have to use the straight cast - the as
won't work.
In the special case of converting to a string, every object has a ToString
, so your third method may be okay if o
isn't null and you think the ToString
method might do what you want.
string s = Convert.ToString(o)
; 5th:string s = $"{o}"
(or equivalently thestring.Format
form for earlier C#) – Earth Engine