Using VB.NET From CSharp

G08L0047 Back when I was teaching .NET to other programmers regularly, I would frequently get the following question from a VB6 programmer moving to CSharp.

“Is there any way of using some of the VB functions I’m used to using within CSharp?”

The answer to this question has two parts, which we will explore today.

The first part to this question is, “I can’t remember the last time I NEEDED to do this.”  Actually, I’ve never needed to do this.  It might have made my life a little easier to replace 3 lines of code with one VB call, but I’m so used to programming in CSharp now that I hardly even notice.

However, the point of this article is not so much that you might need to do this as that you can.  In fact, you can use functionality from any .NET language from any other .NET language using a similar approach.

The first thing you’ll want to do is to add a reference to the language library for the language you want to use in your code.  In the case of VB.NET, you’ll load the Microsoft.VisualBasic.* assemblies

image

Next, you’ll want to browse the “Class View” to find out where each of the functions are.  By doing this, I can see that the MsgBox function is in the “Interaction” class inside of the Microsoft.VisualBasic namespace located in the Microsoft.VisualBasic assembly

image

So to use this function, I add a using statement at the top of my code to use the Microsoft.VisualBasic namespace and call the MsgBox function through the Interaction class

using Microsoft.VisualBasic;

Interaction.MsgBox("Message goes here",
    MsgBoxStyle.OkCancel, "Title goes here");

Related Post

One Response to “Using VB.NET From CSharp”

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear