.NET - Use VB Functions in C#

Yesterday I was working on a .NET website that has a couple of cost calculators in them. The user inputs 10 or so data points and the application will calculate their costs and savings. While working on some validation of the user submitted data, I need to make sure all fields were numeric in value. Well guess what? C# does not have an easy built in function to check for a numeric value. Most of the things I came across were hacks, try/catches or trying to cast the value to something numeric and then seeing the result. I then came across a nice little tip. VB does have a simple IsNumeric function (as does classic ASP). So how can you use this in your C# code?

The answer is very simple. All you need to do is add a reference to a .NET library and then tack on a using statement for the library. You can then use some of the VB functions right inside your C# code.

To add a reference in Visual Studio, just right click on the root item of your project and select Add Reference. From the .NET tab scroll down and find Microsoft.VisualBasic. Then click the OK button. At the top of your code behind file add:

<code lang="csharp[lines]"><br></br>  
using Microsoft.VisualBasic;<br></br>```

That’s it! In my application I can now use the VB function for IsNumeric like so:  

if (Information.IsNumeric(Field1.Text) && Information.IsNumeric(Field2.Text))


//Do something here




comments powered by Disqus