c# - Cast using is twice, or use as once and create a new variable -
in previous question today these 2 different approaches given question answers.
we have object might or might not implement idisposable
. if does, want dispose it, if not nothing. 2 different approaches these:
1)
if(todispose idisposable) (todispose idisposable).dispose();
2)
idisposable disposable = todispose idisposable; if( disposable != null ) disposable.dispose();
mainly, comments sounds consensus 2) best approach.
but looking @ differences, come down this:
1) perform cast twice on todispose.
2) perform cast once, create new intermediate object.
i guess 2 marginally slower because has allocate new local variable, why regarded best solution in case? solely because of readability issues?
my rules of thumb around casting:
- if it's error/bug value not of right type, cast
- otherwise use
as
, in second case - if you're dealing value type, can either use
as
nullable type (for consistency) or useis
, direct cast
note second form doesn't create "new intermediate object". creates new intermediate variable. first approach - it's variable hidden compiler, effectively. it's still present in il stack location, doesn't have representation in source code.
having said of that, in this particular case (where want dispose), darin's approach best one, believe.
Comments
Post a Comment