Craig M Craig M - 4 months ago 9
Vb.net Question

Interface method Implementation and passing using ByRef with VB.NET

I have a C# interface defined as so:

public interface IMenuSecurityService
{
void SetSecurityFlags(List<MenuItem> items);
}


I need to implement this interface in a VB.NET class. When I implement the SetSecurityFlags method with the items parameter passed using ByVal, it compiles.

Public Sub SetSecurityFlags(ByVal items As List(Of L1.Common.Model.MenuItem)) Implements IMenuSecurityService.SetSecurityFlags
' Do some work
End Sub


When I try to implement it with the items parameter passed using ByRef, I get the following compiler error:


Class 'UserRights' must implement 'Sub SetSecurityFlags(items As System.Collections.Generic.List(Of Model.MenuItem))' for interface


Public Sub SetSecurityFlags(ByRef items As List(Of L1.Common.Model.MenuItem)) Implements IMenuSecurityService.SetSecurityFlags
' Do some work
End Sub


I can't seem to figure this one out. Does VB.NET not support this or am I doing something wrong?

Answer

This isn't a VB vs C# issue - it's an issue of your signature being wrong.

Your method doesn't implement the interface, because the interface method has a by-value parameter, whereas your method has a by-reference parameter. You'll have the same problem if you do it in C#:

interface IFoo
{
    void Bar(int x);
}

class Foo : IFoo
{
    public void Bar(ref int x) {}
}

Compilation error:

Test.cs(8,7): error CS0535: 'Foo' does not implement interface member
    'IFoo.Bar(int)'

You haven't explained why you think you need to use a ByRef parameter - it's possible that you don't really understand pass-by-reference vs pass-by-value semantics when it comes to reference types like List<T>. Have a look at my article on the topic for more information.

Comments