Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide Non-CLS compliant code from projects using other languages?

This question is more out of curiosity than a project requirement or a problem.

I have a Non-CLS compliant code in one language (say C#), and I need to use it like that only in my current language (across projects, so making internal is not a choice), and at the same time want to allow other languages (say VB) to be able to call the conflicting implementations without generating compile time error.

For instance,

//C#
public class SecurityService
{
....
    public void Print()
    {
        Console.WriteLine("print"); //This method prints Service Name in lower case
    }

    public void PRINT()
    {
        Console.WriteLine("PRINT");//This method prints service name in UPPER case.
    }
}
'VB.Net 

Module ServiceReader

    Sub Main()
        Dim service As New SecurityService()
        service.print() 'Compile time error: print is ambiguos
    End Sub

End Module

Problem: I need to avoid the compile time error here by somehow hiding one of my 'print' methods from cross language projects (allowing C# projects to call the desired implementation).

Thanks for your interest.

like image 882
Manish Basantani Avatar asked Dec 07 '25 04:12

Manish Basantani


2 Answers

A language like VB.NET offers no escape around its fundamental syntax rule that identifiers are case insensitive. It is not hard to solve, you can simply write a little static adapter method in a case sensitive language like C# that makes the call.

public static class Interop {
    public static void Print2(SecurityService obj) {
        obj.PRINT();
    }
}

You can completely shove it under the doormat by making it an extension method, assuming the language supports it. There will be no actual runtime overhead when the jit optimizer is done with it.

like image 97
Hans Passant Avatar answered Dec 08 '25 17:12

Hans Passant


I'd suggest you make the non-CLS compliant methods/properties internal, but then make another class that isn't CLS compliant to call that stuff and mark that class as [CLSCompliant(false)]

like image 25
Mark Sowul Avatar answered Dec 08 '25 17:12

Mark Sowul