Jules
Jules

Reputation: 4339

Conversion of Inteface from vb.net to c#

I have a control that overrides the protected GetService method and assigns it to the IServiceProvider interface:

Class MyControl
    Inherits Control
    Implements IServiceProvider

    Protected Overrides Sub GetService(t as Type) as Object Implements IServiceProvider.GetService
    End Sub

End Class

I'm struggling to convert this to c#. I've tried implicit v. explicit but I must be getting the syntax wrong.

Upvotes: 1

Views: 406

Answers (3)

JaredPar
JaredPar

Reputation: 754575

There is a bit of a corner issue with VB.Net interface implementation that needs to be considered when porting to C#. A implemented interface method in VB.Net essentially uses both implicit and explicit interface implementations in the same line. This allows for cases like mismatched names and non-public implementations.

For example the following is also a legal implementation of IServiceProvider

Class Example 
  Implements IServiceProvider

  Private Sub GetServiceWrongName(t As Type) As Object Implements IServiceProvider.GetService
    ...
  End Sub
End Class

It translates to roughly the following C# code

class Example : IServiceProvider {
  public object GetServiceWrongName(t as Type) {
    ..
  }

  object IServiceProvider.GetService(t as Type) {
    return GetServiceWrongName(t);
  }

}

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564373

You would do this like:

class MyControl : Control, IServiceProvider
{
     // Explicitly implement this
     object IServiceProvider.GetService(Type t)
     {
          // Call through to the protected version
          return this.GetService(t);
     }

     // Override the protected version...
     protected override object GetService(Type t)
     {
     }
}

That being said, Control already implements IServiceProvider (via Component). You really can just do:

class MyControl : Control
{
     protected override object GetService(Type t)
     {
     }
}

Upvotes: 7

Thomas Levesque
Thomas Levesque

Reputation: 292405

The original VB.NET method is protected, so I guess it's the equivalent of explicit interface implementation in C#:

class MyControl : Control, IServiceProvider
{
     object IServiceProvider.GetService(Type t)
     {
         ...
     }
}

Upvotes: 2

Related Questions