Below are some differences of Direct casting vs 'as' operator?:-
See the below examples:-
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 3rd one is not a casting, but you get the an idea.
}
Below are line wise different:-
1. Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null.
2. Assigns null to s if o is not a string or if o is null. For this reason, you cannot use it with value types (the operator could never return null in that case). Otherwise, assigns o to s.
3. Causes a NullReferenceException of o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.
Happy coding.
krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator