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:

Post a Comment

NOTE: Anonymous Commenting has been turned off for a while... The comment spammers are just killing me...

ALL comments are moderated. I will review every comment before it will appear on the blog.

Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...

I reserve, and will use, the right to not approve ANY comment for ANY reason. I will not usually, but if it's off topic, spam (or even close to spam-like), inflammatory, mean, etc, etc, well... then...

Please see my comment policy for more information if you are interested.

Thanks,
Greg

PS. I am proactively moderating comments. Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...