Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting interface implementation from VB.NET to C#

This may seem like an obvious answer, but I can't seem to find an answer. I have this code in VB.NET:

Public Interface ITestInterface
    WriteOnly Property Encryption() As Boolean
End Interface

And I also have this class and implementation in VB.NET:

Partial Public Class TestClass
    Implements ITestInterface

    Public WriteOnly Property EncryptionVB() As Boolean Implements ITestInterface.Encryption
        Set(ByVal value As Booleam)
             m_Encryption = value
        End Set
    End Property
End Class

I am trying to convert this over to C#. I have the C# Interface converted over just fine, like so:

public interface ITestInterface
{
    bool Encryption { set; }
}

The problem is, how to convert the implementation over. I have this:

public partial class TestClass
{
    public bool Encryption 
    {
         set { m_Encryption = value; }
    }
}

The problem with this is that in C#, it would seem you have to name the function the same as the interface function you are implementing. How can I call this method EncryptionVB instead of Encryption, but still implement the Encryption property?

like image 640
Icemanind Avatar asked Jul 16 '26 00:07

Icemanind


1 Answers

The closest way I can think of is to use explicit implementation:

public partial class TestClass : ITestInterface
{
    public bool EncryptionVB
    {
         ((ITestInterface)this).Encryption = value;
    }

    bool ITestInterface.Encryption { set; }
}

Now, on the surface this might seem like "not the same thing." But it really is. Consider the fact that in VB.NET, when you name a member that implements an interface member something different from what the interface defines, this "new name" only appears when you know the type at compile time.

So:

Dim x As New TestClass
x.EncryptionVB = True

But if x in the above code were typed as ITestInterface, that EncryptionVB property would not be visible. It would be accessible only as Encryption:

Dim y As ITestInterface = New TestClass
y.Encryption = True

This is, in fact, behaving exactly the same as explicit interface implementation in C#. Take a look at the equivalent code:

TestClass x = new TestClass();
x.EncryptionVB = true;

ITestInterface y = new TestClass();
y.Encryption = true;
like image 111
Dan Tao Avatar answered Jul 17 '26 14:07

Dan Tao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!