Which (if any) is more correct? Why?
string someVariable = (string) someOtherVariable;
string someVariable = someOtherVariable.ToString();
string someVariable = someOtherVariable as string;
I’ve used all three, but I don’t have any preference or understanding why one is better than the other.
These are not all examples of casting.
This is a cast:
This is method call:
And this is a safe cast:
The first and third examples are actual casts. The first cast has the potential to throw an
InvalidCastExceptionwhereas the third example will not throw that exception. That is why theasoperator is known as a safe cast.