Parsing strings into other types in C#

What’s the best way of parsing a string into some other type, and making sure nothing more is done if that conversion fails?  A typical way would be:

  try {
    int i = UInt.Parse(s);
  } catch (ex) {
    …blah blah
  }
  next step

but this requires that something happen in the ‘catch’ to prevent doing anything at ‘next step’, and often that is left to a TODO that never gets implemented.  Instead, try this:

  int i;
if (!UInt.TryParse(s, out i)) { return; }
next step

Print Friendly, PDF & Email