Wednesday, June 01, 2005

Using VB Functions from C#

This seems like a no-brainer, but let's say that you're struggling trying to figure out how to do something in C# that you know how to do in VB. Like, maybe taking the right 5 characters of a string.

It's not that you can't do this in C#, because you surely can (it's trivial after working with C# strings for a while), but in a RAD or prototyping environment, you may find yourself wishing that the Right() function existed in C#, and may even be tempted to write one. [Some people would be wondering why you're not just using VB.NET in the first place, but that'$ a different argument].

The point here is that you can access all of the VB.NET functions that you're used to from C# by simply adding a reference to the Microsoft Visual Basic .NET Runtime assembly.

Consider the following code, which at least demonstrates how to get to the Mid and Format functions:

using vb=Microsoft.VisualBasic.Strings;

namespace ConsoleApplication1
class Class1
static void Main(string[] args)
Console.WriteLine(vb.Format(12345, "00000000.00"));

I highly recommend that you explore to see what other familiar functions are available in the Microsoft.VisualBasic namespace (for example, the Microsoft.VisualBasic.FileSystem class could be real helpful!)