1

I am new to vb.net and have an function which takes an typed interface and I want to create an anonymous instance of the interface as the method argument.

Interface

Public Interface MessageHandler(Of T)

    Sub Handle(Message As T)

End Interface

I am not sure if I descripted my problem correctly so here is what i want in Java:

Interface

public interface MessageHandler<T> {

    public abstract void handle(T message);

}

Method call

function(new MessageHandler<Type>() {

    public void handle(Type message) {
        //Do Something
    }

});
1
  • If you know java why not go with C# rather than VB.NET? Commented Aug 23, 2016 at 1:07

1 Answer 1

2

You can't create anonymous implementations of interfaces in .NET. You have to have a concrete implementation, but you can hide it an give the same kind of anonymization easily enough.

I've .NET-ified your naming conventions, but here it is:

Public Interface IMessageHandler(Of T)
    Sub Handle(message As T)
End Interface

Public NotInheritable Class MessageHandler
    Private Sub New()
    End Sub
    Private Class AnonymousMessageHandler(Of T)
        Implements IMessageHandler(Of T)
        Private _handler As Action(Of T)
        Public Sub New(handler As Action(Of T))
            _handler = handler
        End Sub
        Public Sub Handle(message As T) Implements IMessageHandler(Of T).Handle
            Dim h = _handler
            If h IsNot Nothing Then
                h(message)
            End If
        End Sub
    End Class

    Public Shared Function Create(Of T)(handler As Action(Of T)) As IMessageHandler(Of T)
        Return New AnonymousMessageHandler(Of T)(handler)
    End Function
End Class

Or, in C#:

public interface IMessageHandler<T>
{
    void Handle(T message);
}

public static class MessageHandler
{
    private class AnonymousMessageHandler<T> : IMessageHandler<T>
    {
        private Action<T> _handler;
        public AnonymousMessageHandler(Action<T> handler)
        {
            _handler = handler;
        }
        public void Handle(T message)
        {
            _handler?.Invoke(message);
        }
    }

    public static IMessageHandler<T> Create<T>(Action<T> handler)
    {
        return new AnonymousMessageHandler<T>(handler);
    }
}

You can call it (in VB.NET) like this:

MessageHandler.Create(Of Integer)(Sub (x) Console.WriteLine(x)).Handle(42)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.