📜 ⬆️ ⬇️

If there is no difference between the two code options, choose the one that is easier to debug.

In C #, there are two ways to convert objects: use the as operator, which attempts to convert the object and returns a result if successful, null if unsuccessful; or use the transform operator.



Which of these options to choose when you need to immediately use the result of the conversion?

 //  1 var thing = GetCurrentItem(); var foo = thing as Foo; foo.DoSomething(); 

 //  2 var thing = GetCurrentItem(); var foo = (Foo)thing; foo.DoSomething(); 

Now suppose the object thing not a type of Foo . Both options will work incorrectly, but they will do it in different ways.
')
In the first variant, the debugger will throw a 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 ?

In the second variant errors may also occur. If the 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