Reading int and byte values from XElement

The XElement class has a very nice capability that is not very well known - the ability to by typecasted to different types to read data from within.

For example, if I have an XElement instance element, I can write (int)element, and the content of the element will be read, parsed as an int and returned.

If you look at the list of conversions available here, you'll notice that not all possible numeric types are supported. For example, bytes aren't on the list. You might also wonder as to how the nullable types behave - are null'ed values ever returned, and if so when?

I put together a little sample to show a few interesting things:

  • How do I read the value into a byte? 
  • What happens if there is no value?
  • What happens if the value is too large to fit into a byte?

Here's the code, with the output of running it.

string

[] tests = new string[] { "<Root />", "<Root></Root>", "<Root>10</Root>", "<Root>1000</Root>" };
bool[] checkedMathValues = new bool[] { true, false };
foreach (bool checkedMath in checkedMathValues)
{
  foreach (string test in tests)
{
    Console.WriteLine("Converting " + ((checkedMath) ? "(checked)" : "") + ": " + test);
    try
    {
      if (checkedMath)
{
        Console.WriteLine(" " + checked((byte?)(int?)XElement.Parse(test)));
}
      else
      {
        Console.WriteLine(" " + (byte?)(int?)XElement.Parse(test));
}
}
    catch (FormatException e) { Console.WriteLine(" FormatException: " + e.Message); }
    catch (OverflowException e) { Console.WriteLine(" OverflowException: " + e.Message); }
}
}

This is the output produce by the code:

Converting (checked): <Root />
  FormatException: Input string was not in a correct format.
Converting (checked): <Root></Root>
  FormatException: Input string was not in a correct format.
Converting (checked): <Root>10</Root>
  10
Converting (checked): <Root>1000</Root>
  OverflowException: Arithmetic operation resulted in an overflow.
Converting : <Root />
  FormatException: Input string was not in a correct format.
Converting : <Root></Root>
  FormatException: Input string was not in a correct format.
Converting : <Root>10</Root>
  10
Converting : <Root>1000</Root>
  232

Enjoy!