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 str
Use direct cast string s = (string) o;
if in the logical context of your app string
is the only valid type. With this approach, you will get InvalidCastException
and implement the principle of Fail-fast. Your logic will be protected from passing the invalid type further or get NullReferenceException if used as
operator.
If the logic expects several different types cast string s = o as string;
and check it on null
or use is
operator.
New cool feature have appeared in C# 7.0 to simplify cast and check is a Pattern matching:
if(o is string s)
{
// Use string variable s
}
or
switch (o)
{
case int i:
// Use int variable i
break;
case string s:
// Use string variable s
break;
}