as
operator, which attempts to convert the object and returns a result if successful, null
if unsuccessful; or use the transform operator. // 1 var thing = GetCurrentItem(); var foo = thing as Foo; foo.DoSomething();
// 2 var thing = GetCurrentItem(); var foo = (Foo)thing; foo.DoSomething();
thing
not a type of Foo
. Both options will work incorrectly, but they will do it in different ways.NullReferenceException
exception in the foo.DoSomething()
method, and a failure dump will confirm that the foo
variable is null
. However, this may not be in the crash dump. Perhaps the crash dump captures only the parameters that participated in the expression, which in turn led to the exception. Or maybe the variable thing
will go to the garbage collector. You cannot determine where the problem is when GetCurrentItem
returns null
or GetCurrentItem
returns an object of another type other than Foo
. And what is this if not Foo
?thing
object is null
, you will receive a NullReferenceException
when calling the foo.DoSomething()
NullReferenceException
. However, if the thing
object is of a different type, the failure will occur at the type conversion point and will throw an InvalidCastException
exception. If you are lucky, the debugger will show what exactly can not be converted. If you are not very lucky, you can determine where the failure occurred by the type of exception issued.Task: Both options below are functionally equivalent. Which will be easier to debug?
// 1 collection.FirstOrDefault().DoSomething();
// 2 collection.First().DoSomething();
Source: https://habr.com/ru/post/334274/
All Articles