Monday, February 26, 2007

Universal Data Type Conversion Checker Function

.Net Slave - Universal data type checker

"In many different scenarios we need to check if a string can be converted into an integer e.g. This could be when we work with query strings and need to check if they match a certain data type. In VB.NET you can use the IsNumeric and IsDate functions, but that's about it. You are left to your own data type checking logic the rest of the time. It would be cool if we could have a method that could check all data types that is represented by strings such as integers, guids, booleans etc.

Here is a method that does just that. It can check all the string based types and also enums.

...

Let's try some different examples

CanConvert("12", typeof(int)); // returns true

CanConvert("f637a876-9d58-4229-9559-a5e42a95fdac ", typeof(Guid)); // returns true

CanConvert("Backspace", typeof(System.ConsoleKey)); // returns true

CanConvert("10px", typeof(System.Web.UI.WebControls.Unit)); // returns true

CanConvert("red", typeof(System.Drawing.Color)); // returns true"

You've got to love a cool hack...

This C# function (easily translatable into VB.Net) provides a simple, yet universal, type conversion checker function. Sort of like TryParse, but instead using System.ComponentModel.TypeConverter. Check the post out for the code...

(via Onion PeelsLinks 2007-02-25)

No comments: