An example of safely converting any object to any type with a TryConvert() function.
string TestObject = "abc123"; int SomeInteger = int.TryParse(TestObject, out SomeInteger) ? SomeInteger : default(int); long SomeLong = long.TryParse(TestObject, out SomeLong) ? SomeLong : default(long); decimal SomeDecimal = decimal.TryParse(TestObject, out SomeDecimal) ? SomeDecimal : default(decimal); float SomeFloat = float.TryParse(TestObject, out SomeFloat) ? SomeFloat : default(float); double SomeDouble = double.TryParse(TestObject, out SomeDouble) ? SomeDouble : default(double); bool SomeBoolean = bool.TryParse(TestObject, out SomeBoolean) ? SomeBoolean : default(bool);
I wish I could take credit for this, but I found it a few years ago. I'm seeing it used a lot now on StackExchange answers as well. It works with all the basic types in C# including unsigned and DateTime as well.
Not a lot of explanation is given for why this works though, so here's a breakdown for the order of events...
- type SomeType is executed prior to anything else to give everything right of the = a place to go.
- type.TryParse() is called with the object to parse and the variable from the first step
- Should TryParse success, the value is now stored in the variable. Should it fail, the variable remains uninitialized (whatever the type's default value is).
- TryParse() returns true or false based on the success to the tertiary (?) operator.
- If the TryParse() result was true, the variable (now containing a value) itself is assigned to itself.
- If the TryParse() result was false, a default value (typically 0 for numeric types) is assigned.
Either way the TryParse() turns out, the variable is now defined with a non-null value.