TryConvertTo<T> C# Helper


C# Logo

This snippet of code has been in my arsenal for many years. I am not sure where I first learned it or heard of it, but it finds its way into nearly all of my projects. Using Generic types it allows for quick and accurate conversions from any data-type to any other data-type. If the conversion cannot happen the default of the targeted data-type is returned.


I find this snippet most useful when scrubbing user data or ensuring data from an external data-source is valid. This works with any primitive data-type and can save you many hours of troubleshooting if used to scrub data.

Since I have implemented this as a static class you can call it on any data-type like below.


String to Int:

Returns: 123 type cased to an int

Bad String to Int:

Returns: 0 type casted to an int since abc123 cannot be successfully converted

Variable to T

Returns: 123 type casted as an int


7 views

©2020 by Justin Wilson