Calling a C# DLL from VB.NET

Introduction

Often times the need arises to make use of a C# program's functionalities inside of a VB.NET program, and vice versa. Usually in this case, a Class Library is created that exposes all the necessary methods to the calling application.

If you do not know what a class library is, have a look here.

With this article, I will demonstrate how to use a C# Class Library from within a VB.NET project. This is going to be fun, so hold tight!

Design

C#

Open Visual Studio 2012 and create a new C# Class Library project. Give it a name such as CallMeFromVB. Once the project is loaded, add a new Windows Form to the project. Give the form a name like frmCMFVB. Add one label to the form named lblCallInfo and set the properties not to have any Text and to be able to resize to fit its text. Also, make the label's Modifier property Public. This will allow other programs to access and change the label externally.

This form will be launched from inside VB.

Rename the ClassLibrary1 class to ClassInCSharpProject.

VB.NET

Create a new Visual basic Windows Forms application and name it VBCallingApp. Name the default form frmVBCA.

Code

C# Class Library

Once we have followed all of the above steps correctly and given each object the same name as I have, your class library will include a namespace named CallMeFromVB. The reason why I mention this here is because when we will import our C# class library's functionalities into our VB.NET project, we will have to reference this namespace in order to get access to the class(es)  inside this namespace from C#.

Namespaces

Add the following using statement above your ClassInCSharpObject's class declaration:

using System.Windows.Forms; //Imported For MessageBox

Interfaces

Add the following Interface for our CallMeFromVB namespace, just above the class declaration:

    //Made Project OutPut Type Class Library
    //Project Properties, Output Type - Class Library
    //Or Can Make Class Library Project and Add Form & Form References

    public interface interfaceClassInCSharpProject

    {
        int ShowFormInSideVB(string sCallerInfo);
        int CountForms();

    }

Having an interface inside the namespace allows us to expose our class' methods to any external caller. These two methods, which will be added shortly, are the only two methods in our class. One will be used to show the form, and the other method will be used to count how many times the form was shown. Let us set up our class properly now.

Make sure that your class' access modifier is Public. Being public means that we can expose all our stuff to any external caller. The class constructor should also be empty, leave it like that as we won't be doing anything in there.

Create the next variable:

        public static int intFormCounter = 0; //Count How Many Times Form Has Been Displayed

As the name implies, it will be used to count the amount of forms loaded and shown.

Add the next two methods:

        public int ShowFormInSideVB(string sCallerInfo) //Show Form Inside VB
        {
            
            //Instantiate Form Object
            frmCMFVB frmNew = new frmCMFVB();

            //Set Text For Label On frmCMFVB
            frmNew.lblCallInfo.Text = sCallerInfo; //Made Label Modifier Property Public

            //Show the Form  
            frmNew.Show();
            
            return 0; //Return 0

        }

        public static int CountForms() //Count Forms Shown
        {
            
            intFormCounter++; //Increment Form Counter

            return intFormCounter; //Return Form Counter

        }

ShowFormInSideVB creates a new form object and shows it. the sCallerInfo parameter is used to put text onto the label.

CountForms simply counts how many times the form has been shown. You might think it strange that I haven't referenced this method from inside this code, but it is not necessary. We will make use of the CountForms method from within our VB project.

If you were to build your project now, it would produce the resulting DLL file. This file we will need to reference from VB. Let us start with our VB.NET project now.

VB.NET calling application

References

Click on Project, Add Reference..., Select the Browse tab. Browse to the CallMeFromVB.dll file ( located in either the release folder or Debug folder of the project ). Select it and click OK.

C# Class Library Reference

Figure 1 - C# Class Library Reference

Namespaces

After we have added the project reference, we also need to import it into our code. Let us do that now:

Imports CallMeFromVB.ClassInCSharpProject 'Import C# Class Library

This imports the C# library into our VB.NET project. We reference the namespace ( CallMeFromVB ), as well as the class (ClassInCSharpProject ) in that namespace.

Events

Add the next code segment to create the Form_Click event:

    'Added Project reference To CallMeFromVB.dll

    Private Sub frmVBCA_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click

        Dim objcsClass As CallMeFromVB.ClassInCSharpProject 'Create & Instantiate C# Library

        objcsClass = New CallMeFromVB.ClassInCSharpProject


        If CountForms() >= 5 Then 'Make Use of C# Library's CountForms Function To Determine How Many Times the C# Form Has Been Loaded

            MessageBox.Show("Form Limit Exceeded") 'Inform User

            intFormCounter = 0 'Reset C# Library Counter

        Else

            objcsClass.ShowFormInSideVB("C# Form " + intFormCounter.ToString() + " Called From VB") 'Show C# Form and Display Form Counter

        End If

    End Sub

When the Visual Basic form is clicked, it creates and instantiates the C# library object. We make use of the C# library's CountForms function to determine how many times the C# form has been loaded. If it exceeds 5, it informs the user; else, it makes use of the ShowFormInSideVB method to show the form. We keep track of the number of times the form has been loaded through the intFormCounter variable.

I am including both projects below, just in case you missed a step or two.

The same logic can obviously be applied if you have the need to make use of a VB.NET class library inside a C# application. Feel free to experiment a little. Without experimentation, nothing will be learned.

Conclusion

As you can see, it is not difficult to make use of a C# library inside a VB.NET project. This is obviously just a tiny example to show you the ropes. I hope you have enjoyed my article. Until next time, cheers!



Related Articles

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds