Z Code

Access the Power of VB.NET From C#

C# now provides many of the features VB developers have enjoyed for years. Learn how to plug the rest of VB's power into your C# apps.

Technology Toolbox: VB.NET, C#

The dust has settled, and an uneasy peace lies across the land. Visual Basic .NET developers continue to struggle to remain loyal to VB. They know intellectually that VB is truly a first-class language in .NET—but somehow they still don't quite believe it. Meanwhile, C++ developers have largely stayed aloof from the language wars, too busy trying to decode a multitude of language extensions such as:

typedef __gc __managed __confused 
   char *[] __volatile __mismanaged 
   x;

And C# programmers are as happy as a kid with the newest toy on the block, mostly because they have the newest toy on the block.

This is how things stand these days, midway through the "Everett" age. (Everett was Microsoft's code name for Visual Studio 2003.) Even now, you hear the VB.NET developer community talking about how VB.NET is a serious language at last, truly as good and as powerful as C#.

What I find odd is that you rarely hear C# programmers talking about how their "C-type" language is finally as powerful as BASIC. After all, BASIC developers have long enjoyed a number of important language features absent in C++. Moreover, C++ developers had to spend a lot of extra time coding and debugging these features. For example, the "innovations" of C# include garbage collection and memory management. These make programs less prone to memory leaks and buffer overflows—and they've been a standard feature of BASIC for a long time, along with other features that still aren't built into C#.

However, .NET makes it possible for C# developers to take advantage of all the power of Visual Basic .NET. This is because .NET locates most of VB's language features in the .NET Framework underlying all .NET languages—specifically, in the Microsoft.VisualBasic.Runtime namespace. You can access these features from C# by adding a reference to the Microsoft.VisualBasic.Dll assembly and using the Project | Add Reference command (see Figure 1). Save some typing by adding a using reference to the namespace:

using Microsoft.VisualBasic;

C# developers tapping into VB.NET's power most likely will want to start with its financial operations, which are critical for many business applications. VB.NET, like BASIC, is often used for business application development. For example, this C# code enables you to calculate a payment on a loan. In this case, it's a loan for $100,000 at 5 percent interest over 30 years, compounded monthly:

Console.Write("Your payment is: ");
Console.WriteLine(Financial.Pmt(.05/12,
   30*12,100000,0, 
DueDate.BegOfPeriod).ToString("$0.00"))
   ;

With IntelliSense to help you out, this implementation is much easier and faster than coding the equations yourself (not to mention the time it would take to look them up and test the code to make sure you implemented them correctly).

Let VB Let C# Give You the Business
You might have to go back to your college economics text to understand some of the available financial functions (see Table 1). Don't fret if you're a few years away from your business courses. Microsoft has decent documentation on all of these functions. Look for it in the Visual Basic Language Reference in the MSDN documentation.

This is only the beginning—many other VB.NET functions can make your life easier in C#. One of my favorites is the one that provides late-bound access to COM objects.

There are plenty of examples of how to interact with COM objects by adding a reference to their type library (using an interop assembly). This is fine in most cases. Occasionally, however, you might need to define the COM object you wish to reference at run time, then access it using late binding. TheVB.NET CreateObject function makes it trivial to obtain a reference to a COM object using the Program ID. This example shows how to access the UserName property of the Excel Application object:

Object Excel = 
   Interaction.CreateObject
   ("Excel.Application", null);
Console.WriteLine(Excel.GetType().
   InvokeMember("UserName", 
   BindingFlags.GetProperty | 
   BindingFlags.Public, null, Excel, 
   null));
// or use:
Console.WriteLine(Interaction.
   CallByName(Excel,"UserName", 
   CallType.Get,null));

You can save a few keystrokes by using the CallByName function for late binding. This approach is a bit more intuitive if you don't do late binding often.

VB also lets you check for numbers. For instance, you might need to find out whether you can convert a string into a number using the IsNumeric function:

Console.Write("Is 4.23 a number? ");
Console.WriteLine(Information.IsNumeric
   ("4.23"));
Console.Write("Is X4.23 a number? ");
Console.WriteLine(Information.IsNumeric
   ("X4.23"));

Suppose you're in a rush and don't want to look up and figure out the cryptic formatting rules for the IFormattable interface. You can check out the individual format functions Strings.FormatCurrency, Strings.FormatDateTime, Strings.FormatNumber, and Strings.FormatPercent. Or perhaps you need some quick user input at a given point in your application. The VB Interaction.InputBox function provides a one-line solution. Maybe you need some easy shortcuts to common Registry operations. If so, try the Interaction.GetSetting, Interaction.GetAllSettings, Interaction.DeleteSetting, and Interaction.SaveSetting functions.

Watch Out for Visual Studio 2005
It's not only fun helping C# developers catch up with VBers, but useful as well. Still, it's a fact that at the moment, the two languages really are similar in terms of both features and power. You might have seen the numerous papers and technology previews of Visual Studio 2005 (the development system formerly known as Whidbey). However, it's too early to evaluate accurately the changes coming to VB.NET and C# (see the sidebar, "Language Choice Will (or Won't) Matter"). There's still plenty of time for Microsoft to make changes, add features, or even remove some if it can't get them to work reliably by shipping time. For example, that's what happened to "edit and continue" in the current version of Visual Studio .NET.

However, two general ideas are apparent already in regard to the two languages themselves. First, both VB.NET and C# will continue to be full-featured .NET languages. There aren't going to be any "deal-breaker" features missing from one language that will drive adoption to the other. Second, VB.NET will be changing to make it more like "BASIC"—in the sense that the language will be gaining new keywords to simplify common tasks and bring the language to a higher level of abstraction. This should make it easier to use, harkening back to BASIC's origin as a teaching language. One way this will occur is with the addition of "My" classes.

Consider the example of writing some text into a file. You need some pretty sophisticated code to express such a simple concept in today's Visual Studio:

StreamWriter sw = new
   StreamWriter("f:\\temp\\oldway.txt")
      ;
sw.WriteLine("This is a single line " +
   "of text in a file");
sw.Close();

This isn't a great deal of code, but writing it successfully requires a substantial understanding of .NET file I/O theory. You need to understand the relationship between streams and files, then wade through numerous overloaded functions to figure out how to perform this task. On the other hand, the same thing in Visual Studio 2005's rev of VB.NET takes only one line of straightforward code:

My.Computer.FileIO.WriteAllText
   ("f:\temp\file1.txt", _
   "This is a brand new file with " & _
   "some text", False)

Simplify Your Architecture
The My classes in Visual Studio 2005 are designed to speed application development, not only by shrinking the amount of code required, but also by providing a simplified class library. The new library reduces the number of objects and methods you have to search through to accomplish common tasks. It also provides a simplified architecture for those tasks. The My classes cover a variety of areas, including cool audio features, simplified clipboard access, and numerous computer features. These include mouse, keyboard, serial support, simplified printing, and much more.

C# developers will surely continue to be able to access the current VB.NET runtime features. And certainly the My features will be accessible from C#. However, it's not clear at this time how easy it will be. Suppose a C# developer wants to implement the earlier file-writing example. In the Visual Studio 2005 technology preview, you would do this:

Computer mycomputer = new Computer();
FileIO myfileio = mycomputer.FileIO;
myfileio.WriteAllText(
   "f:\\temp\\file2.txt",
   "Here is some text to write " +
   "into a file",false);

That's not as simple as it is in the new VB.NET, which provides built-in compiler support for the My class library. However, it might become easier by the time Visual Studio 2005 ships. But even if the My classes remain as they are, C# programmers should learn how to access them, given their timesaving potential.

All the talk about VB.NET finally becoming a first-class .NET language makes it easy to overlook a basic fact: VB retained many of its historic strengths when it migrated to .NET. The big change is that, for the first time, C++ and C# programmers can take advantage of some of these features. Okay, maybe it's a little embarrassing for you to include a reference to Microsoft.VisualBasic in your ultra-cool C# application, but I encourage you to do so with pride. VB.NET is part of the .NET Framework, and the only thing you should truly be embarrassed about is ignoring a feature that can save you time and money.

comments powered by Disqus
Most   Popular