0

There are two alternatives I am considering as guard clauses to only allow some code to run if I have an object of proper type:

var targetObject = eventArgs.Value as MagicType;

if (targetObject != null)
{
    DoStuffWith(targetObject);
}

or else:

if (targetObject is MagicType)
{
     // DoStuffWith(targetObject);  // not quite. Actually:
     DoStuffWith((MagicType)targetObject);
}

Looking at both alternatives, they seem pretty equivalent, but I know the operations (as vs is) are conceptually different.

So the question is: which one should be preferred? Is that choice dependent on scenario? And why?

heltonbiker
  • 26,657
  • 28
  • 137
  • 252
  • 1
    They are not equivalent because in the second option `DoStuffWith` must accept object (you do not pass the casted object) – Flat Eric Jul 30 '15 at 18:32
  • If `DoStuffWith` requires a `MagicType`, then `as` with `null` check is better, but if you don't *need* the object as a `MagicType`, then `is` is fine. – crashmstr Jul 30 '15 at 18:33
  • http://stackoverflow.com/questions/2139798/does-it-make-sense-to-use-as-instead-of-a-cast-even-if-there-is-no-null-check?rq=1 – user2864740 Jul 30 '15 at 18:35
  • 1
    If you're going to use the object after casting then `as` is good. If you're only checking if it can be cast to other type then `is` would do the job and also provide you with performance advantage. – vendettamit Jul 30 '15 at 18:35
  • @FlatEric and @crashmstr: actually the method needs `MagicType`, so I corrected the second code block. – heltonbiker Jul 30 '15 at 19:09

0 Answers0