Get Started!

C# Cleaner Convert.To

Here's my prefered way of casting string to ints / longs etc.

When casting values in C# you can use the var nVal = Convert.ToInt16(cVal) method, in this example to an int. However this throws an exception, so you find yourself needing to wrap each conversion in a try / catch.

Using int.TryParse

This is what I use instead

var nVal = -1;

if( !int.TryParse( cVal, out nVal ) ){
  // cast failed
  return;
}

For me this is more legible and much cleaner.

Using long.TryParse

This is what I use instead

var nVal = -1L;

if( !long.TryParse( cVal, out nVal ) ){
  // cast failed
  return;
}

Note the only real difference is that I've use an initializer of -1L the L will tell the compiler that the Type is long allowing me to use var keyword syntax.

Using DateTime.TryParse

Here's an example of extracting start & end dates from some TextBox control, using UK format dd/mm/yyyy.

var startDate = DateTime.Today.AddMonths(-1);
if( !DateTime.TryParse( tbStartDate.Text, out startDate ) ){
  // Failed
  startDate = DateTime.Today.AddMonths(-1);
}

var endDate = DateTime.Today;
if( !DateTime.TryParse( tbEndDate.Text, out endDate ) ){
  // Failed
  endDate = DateTime.Today;
}