This question already has an answer here:
I have a class that has an interface in it like so:
public class hcmTerminal {
... Code
public interface onDataReceived {
void isCompleted(bool done);
}
}
inside this class I I have the public property:
public onDataReceived mDataReceived;
then I have a function to set the delegate:
public void setDataReceived(onDataReceived dataReceived) { mDataReceived = dataReceived; }
Inside the hcmTerminal class I am am calling the delegate :
mDataReceived.isCompleted(true);
But I can't figure out the syntax to actually get when that delegate gets called, In java I can go:
myTerminal.setDataReceived(new hcmTerminal.onDataReceived(){
@Override
public void isCompleted(boolean done){
... Code
}
});
But if I try that in C# I get:
Cannot create an instance of the abstract or interface 'hcmTerminal.onDataReceived'
I haven't had to create a interface in C# before. this code is coming from how I implemented it in Java.
By using events you can accomplish that by
class HcmTerminal {
public event Action<bool> OnDataReceived;
public void Launch()
{
OnDataReceived?.Invoke(true /*or false*/);
}
}
You can then do:
var myTerminal = new HcmTerminal();
myTerminal.OnDataReceived += (isCompleted) => {};
Define a class implementing the interface:
class MyDataReceived : hcmTerminal.onDataReceived {
public void isCompleted(bool done) {
Console.WriteLine("call to isCompleted. done={0}", done);
}
}
Now you can call myTerminal.setDataReceived(new MyDataReceived())
However, this is a Java solution coded in C#, not a "native" C# solution. A better approach is to define a delegate in place of an interface:
public class HcmTerminal {
... Code
public delegate void OnDataReceived(bool done);
}
This would let you use multiple C# features for supplying delegate implementation, such as providing a method name, supplying an anonymous delegate, or using a lambda:
myTerminal.setDataReceived((done) => {
Console.WriteLine("call to isCompleted. done={0}", done);
});