posts - 76, comments - 26, trackbacks - 0

IsNumeric in C#

Like I said previously…. going back to the VB6 world was shocking, but it did remind me of a few cool VB things that I’d kinda forgotten about.  These aren’t specific to version 6 and are present in VB.NET of course.  The first that comes to mind is IsNumeric.  VB has a slew of Is[…] helper functions built in.  Notice I didn’t qualify where it’s baked in.  The one of the cool features of the .NET Framework as a platform (though I’m still not convinced how overly valuable it actually is….) is language agnosticism.

The common language class library makes this possible.  With .NET, all of the goodnesses that were previously baked into various languages and their compilers are all moved into a common set of libraries – this isn’t news to anyone (this sounds like an article from 2002).  What might not be obvious to hardcore C# developer’s is there’s a great deal of handy functions in the Microsoft.VisualBasic assembly/namespace…. such as IsNumerc.

Scott and Chris have a very interesting discussion about a ton of things – this being one of them – on the last Hanselminutes podcast.  It made me wonder – why is it taboo to use VB stuff inside of non-VB things (like C#).  Nowadays, it’s totally possible, easy, and no reason not to other than C# developers having to look at the words “VisualBasic” everyday.

I’ve seen a ton of custom IsNumeric implementations…. most of them something to the effect of…

try
{
    double.Parse(num);
    return true;
}
catch
{
    return false;
}

There are a lot of things wrong with this as Scott points out. From now on, I’m going to use the following and quitely wait for the waterless arguments to flow in as to why this is bad….

if ( Microsoft.VisualBasic.Information.IsNumeric(num) )
{
    //..
}

There are a lot of nice things about this – the namespace the VB chose not being one of them, but don’t assume there isn’t any try/catch’less magic going on.  Take a look in Reflector and you’ll see that at the core, there’s still a last ditch “otherwise, parse the darn thing and see if it dies” block in there.

Print | posted on Wednesday, September 27, 2006 12:00 AM | Filed Under [ microsoft .net ]

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 5 and 1 and type the answer here:

Powered by: