Dot Net Capsules

A Capsule on .NET, everyday, keeps you .NetHealthy!!!!

My Photo

Programmer. Visit my new blog at

Tuesday, May 10, 2005

Language Interop - from C# to VB.NET

In one interview I was asked a question on language interoperability. The question was:
Suppose you define two functions in a C# class: one is having signature “public string hello()” and another is having signature “public string Hello(string name)”. Both the methods has the same name but different case and different signature. Now if you access one of these methods from VB.NET code, what will happen?

I immediately replied that code would compile successfully. Why? Because the method signature is different the code would compile successfully. If method signature is same and method names are different only in their case, i.e. one method name is “hello” and another is “Hello” then VB.NET code will not be able to access this method.
Although I have never tried this I was able to answer it. Then I thought let me try this and see what happens. So I created two projects: a C# class library and a VB.NET console application that access this C# class library. Following is the code:

using System;
namespace CSharpLibrary
public class WelcomeMessageProvider
public WelcomeMessageProvider()

public string welcomeMessage()
return "Hello world";

public string WelcomeMessage(string name)
return "Hello world, " + name;
Imports CSharpLibrary
Module Module1

Sub Main()
Dim wmp As WelcomeMessageProvider = New WelcomeMessageProvider
End Sub

End Module

If we compile the CsharpLibrary and then VBApplication, then it would compile successfully. But suppose we remove the string parameter from the second “WelcomeMessage” method then while compiling the VBApplication following error would come:
D:\Ashish\dotnet\Practise\LanguageInteropPractise\VBApplication\Module1.vb(7): Overload resolution failed because no accessible 'welcomeMessage' is most specific for these arguments:
'Public Function WelcomeMessage() As String': Not most specific.
'Public Function welcomeMessage() As String': Not most specific.

For VB.NET application here there are two methods with the same name, since VB.NET is case-insensitive.
If you don’t want this to happen, you should not define methods that differ only in their case.
You can apply the CLSCompliantAttribute attribute to your C# assembly. So that even by mistake you define two methods with different signature and same name that differ only in their case, your assembly would not compile. When you try to compile your C# assembly it will give following compilation error:

D:\Ashish\dotnet\Practise\LanguageInteropPractise\CSharpLibrary\Class1.cs(20): Identifier 'CSharpLibrary.WelcomeMessageProvider.WelcomeMessage(string)' differing only in case is not CLS-compliant


Post a Comment

<< Home

You Visitor Number:
Free Web Site Counter
Free Counter
free counters