Reply to thread

Implementing Interface Members


There are differences between implementing interfaces in VB and C#. VB allows you to implement a function of an interface with whatever name and visibility you like. C# only allows either a public method with the same name as the interfaces method or an unnamed private method. Sometimes there may be no direct conversion when it comes to interface implementation.

[code]

[Color=Magenta]<VB>[/Color]

[Color=blue]Interface[/color] IExample

    [Color=blue]Sub[/color] DoStuff()

    [Color=blue]Sub[/color] DoOtherStuff()

[Color=blue]End Interface[/color]


[Color=blue]Class[/color] Implementor

    [Color=blue]Implements[/color] IExample


    [Color=Green]Most common scenario: Public/Same name as interface method.[/Color]

    [Color=blue]Public Sub[/color] DoStuff() [Color=blue]Implements[/color] IExample.DoStuff

    [Color=blue]End Sub[/color]


    [Color=green]Custom name and private visibility.[/color]

    [Color=blue]Private Sub[/color] RandomName() [Color=blue]Implements[/color] IExample.DoOtherStuff

    [Color=blue]End Sub[/color]

[Color=blue]End Class[/color]



[Color=Magenta]<C#>[/Color]

[color=blue]interface[/color] IExample

{

    [color=blue]void[/color] DoStuff();

    [color=blue]void[/color] DoOtherStuff();

}


[color=blue]class[/color] Implementer:IExample

{

    [color=green]// Most common scenario: Implicit Implementation

    // What method of what interface this method implements is implied by its

    // name (must be public).[/color]

    [color=blue]public void[/color] DoStuff() {}


    [color=green]// Explicit Implementation

    // This function is private and has no name, and can not be accessed directly, but only

    // through the interface (you must cast to IExample).[/color]

    [color=blue]void[/color] IExample.DoOtherStuff() {}

}

[/code]


Back
Top