Converting value types in C# with Parse and TryParse

Converting values from one type to another in C# is generally pretty straightforward: most objects contain a ToString() method which handles conversion to strings (at least for simple value types), and most value types have a Parse() method to read a string representation of their type.

Of course, dealing with invalid inputs can be a pain – the Parse() method will throw an FormatException if you, for example, pass “a zillion” to int.Parse(), so you need to wrap the code in a try/catch block:

   1:  int output = 0;
   2:  try
   3:  {
   4:      output = int.Parse("a zillion");
   5:  }
   6:  catch(FormatException)
   7:  {
   8:      // error handling goes here
   9:  }
  10:  Assert.AreEqual(0, output);

Version 2.0 of the .NET Framework made this a lot simpler with the addition of the TryParse() method:

   1:  int output;
   2:  int.TryParse("a zillion", out output);
   3:  Assert.AreEqual(0, output);

Note that it wasn’t necessary to initialize output here – if the call to TryParse fails, the output variable is set to 0. In the case of DateTime, the variable is set to DateTime.MinValue.)

Sadly, converting strings to Enums is still a pain, but doable – the try/catch concept still holds, but you need to watch out for ArgumentExceptions, and there are some casting and parameters to consider:

   1:  public enum Stuff
   2:  {
   3:      Something,
   4:      SomethingElse
   5:  }
   6:   
   7:  [Test]
   8:  public void EnumParsingTest()
   9:  {
  10:      Stuff output = Stuff.SomethingElse;
  11:      try
  12:      {
  13:          output = (Stuff) (Enum.Parse(typeof (Stuff), "Something"));
  14:      }
  15:      catch(ArgumentException)
  16:      {
  17:          // error handling
  18:      }
  19:      Assert.AreEqual(Stuff.Something, output);
  20:  }

Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *