.Net & SharePoint '07

Technical blog for .Net and all SharePoint 2007 related Information

About the author

Me(Prince) and my wife are B.E in I.T & C.S.E respectively.  I a certified MCPD: Web from 2007 Dec. I am Intrestes in Web Application, MOSS, EPM, etc.
Now working with Deira International School, as IT Application & Help Manager. I have started my career as "Software Developer" @  REACH Sewn Technologies and Consulting Pvt. Ltd, Bangalore India from Oct 2004 to Feb 2006, then as "Web & Intranet Developer" @ Fosroc International Ltd, Dubai from April 2006 to Sep 2009.
You can catch me on mail@jpy-tech.com or mail@princepy.com. Or on 00971 - 50 - 4284530 

Google Translate

Tag cloud

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

RecentComments

Comment RSS

Google Your Location


C# equivalent of VB's IsNumeric()

Int32.Parse()

First up is the Int32.Parse() method. It's fairly straightforward, you pass it a string parameter and it tries to parse it as an integer. If the string can't be converted to an int then the method fails and an exception is thrown:

try
{
   int result = int.Parse("123");
   Debug.WriteLine("Valid integer: " + result);
}
catch
{
   Debug.WriteLine("Not a valid integer");
}

Here we're using the int data type which is just a C# synonym for Int32. It's a 32-bit integer so will successfully parse any whole number between –2147483648 and 2147483647 inclusive. The  Parse() method is also available for other integral types, floating point types and decimals.

This is a good solution, but it's quite verbose and includes the overhead of throwing an exception if the conversion fails.


Int32.TryParse()

The Int32.TryParse() method is a .NET 2.0 refinement of Int32.Parse(). It's more succinct and doesn't throw an exception if parsing fails. Here's how it works:

int result;
if
(int.TryParse("123", out result))
{
   Debug.WriteLine("Valid integer: " + result);
}
else
{
   Debug.WriteLine("Not a valid integer");
}

IsNumeric()

That's right, you can call VB's IsNumeric() function directly from C#.

First add a reference to the Visual Basic compatibility assembly, Microsoft.VisualBasic.dll, which contains the function's implementation:

You can now access any of the methods from the Microsoft.VisualBasic.Information class, including IsNumeric(), like this:

using Microsoft.VisualBasic;
// ...... bool result = Information.IsNumeric("123");

This isn't really a recommended approach because these classes were included in .NET to provide backward compatibility with legacy VB code.


Categories: c#
Posted by prince on Wednesday, June 18, 2008 4:01 PM
Permalink | Comments (0) | Post RSSRSS comment feed