Ilya Cherevkov Ilya Cherevkov - 4 months ago 17
C# Question

C# Calling base method from interface method

I am starting to learn C# and can not figure out how to call base class method from within interface method. In this particular case, I need to somehow call

sendData
from within
onRecieve
method.

WebSocketBase.cs

using WebSocketSharp;
using System;
using System.Collections.Generic;
using System.Threading;

class WebSocketBase
{
private WebSocket webSocketClient = null;
private WebSocketService webService = null;
private string url = null;

public WebSocketBase(string url, WebSocketService webService)
{
this.webService = webService;
this.url = url;
}

public void start()
{
webSocketClient = new WebSocket(url);
webSocketClient.OnError += new EventHandler<WebSocketSharp.ErrorEventArgs>(webSocketClient_Error);
webSocketClient.OnOpen += new EventHandler(webSocketClient_Opened);
webSocketClient.OnClose += new EventHandler<WebSocketSharp.CloseEventArgs>(webSocketClient_Closed);
webSocketClient.OnMessage += new EventHandler<MessageEventArgs>(webSocketClient_MessageReceived);
webSocketClient.ConnectAsync();
}

private void webSocketClient_MessageReceived(object sender, MessageEventArgs e)
{
webService.onReceive(e.Data);
}

public void send(string channel)
{
webSocketClient.Send(channel);
}

public void sendData(string data)
{
send("data");
}

}

interface WebSocketService
{
void onReceive(String msg);
}


Logic.cs

class Logic : WebSocketService
{
public void onReceive(string msg)
{
Console.WriteLine("Received message")
}
}

Answer

So it looks like your WebSocketBase has a dependency on the service. Why not make the service know about what WebSocketBase is sending it messages?

interface WebSocketService
{
    void onReceive(WebSocketBase sender, String msg);
}

class Logic : WebSocketService
{
    public void onReceive(WebSocketBase sender, string msg)
    {
         sender.send("blah");
    }
}

class WebSocketBase
{  
    ...

    private void webSocketClient_MessageReceived(object sender, MessageEventArgs e)
    {
        webService.onReceive(this, e.Data);
    }

    public void send(string channel)
    {
        webSocketClient.Send(channel);
    }

    ...    
}