Using an interface from class in C# [duplicate] - c#

This question already has answers here:
Counterpart to anonymous interface implementations in C#
(5 answers)
Closed 5 years ago.
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);
});

Related

CRTP implementation in c# [duplicate]

This question already has answers here:
New keyword: why is the derived method not called?
(2 answers)
C# & generics - why is method in base class called instead of new method in derived class?
(4 answers)
Closed last month.
I'm trying to implement Curiously recurring template pattern(CRTP) in c#.
here is some code i wrote.
using System;
using System.Collections;
using System.Collections.Generic;
// Curiously recurring template pattern in c#
namespace MyApp
{
public class Program
{
public static void Main (string[] arg)
{
new Child().CallChildMethod();
}
}
public abstract class Base <T> where T: Base<T>, new ()
{
// Game loop
void Upate ()
{
Method ();
}
public void CallChildMethod ()
{
T t = (T)this;
t?.Method ();
}
public void Method ()
{
Console.WriteLine ("Base Method!");
}
}
public class Child: Base <Child>
{
public new void Method ()
{
Console.WriteLine ("Child Method!");
}
}
}
In output i'm getting
Base Method!
but my code should print
Child Method!
any idea?
Expected
I want to access child class object in base class instead of overriding base methods and please suggest is there any other way to do the same?.

Implementing a custom event handler from interface [duplicate]

This question already has answers here:
C# Language Design: explicit interface implementation of an event
(4 answers)
Closed 5 years ago.
I am in the process of creating a system that can receive messages from a variety of different sources.
Using the interface approach, I am adding a custom event which will pass the message back to the calling application.
I've used Vistual Studio's "scaffolding" using Ctrl-. to provide the implementation for the concrete class, but its added the add and remove elements but I dont really know how to wire that bit up.
Interface class
public class MessageEventArgs : EventArgs
{
public Message { get; set; }
}
public interface MessageBroker
{
void Start();
event EventHandler<MessageEventArgs> OnMessageReceived;
}
Implementation class
public class MessageSourceA : MessageBroker
{
event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived
{
add
{
// What goes here
}
remove
{
// What goes here
}
}
void MessageBroker.Start()
{
}
}
Main Program
static void Main(string[] args)
{
MessageBroker sourceA = new MessageSourceA ();
sourceA.OnMessageReceived += sourceA_OnMessageReceived;
}
private static void sourceA_OnMessageReceived(object sender, MessageEventArgs e)
{
// Do stuff with message
}
Thanks...
You could normally implement from interface.
public class MessageSourceA : IMessageBroker
{
public void Start();
public event EventHandler<MessageEventArgs> OnMessageReceived;
}
I suggest you to rename MessageBroker to IMessageBroker as its a naming convention. Since "I" helps to differentiate between class and interface when looking at code.
If there is proper reason to implement interface explicitly you need private event handler.
private event EventHandler<MessageEventArgs> _onMessageReceived;
event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived
{
add
{
_onMessageRecieved += value;
}
remove
{
_onMessageRecieved -= value;
}
}

Lambda implementing Interface

In the book I'm reading "Head First Design Patterns", Command Pattern there is an example where they're substituting an Interface with Lambda.
Is this something that only Java is capable of?
Here is an example
From the book:
// Receiver
public class Light
{
public void On() {
Console.WriteLine("Lights on");
}
public void Off() {
Console.WriteLine("Ligts off");
}
}
// Command interface
public interface ICommand
{
void Execute();
}
// Concrete command
public class SimpleCommandLightOn : ICommand
{
private readonly Light light;
public SimpleCommandLightOn(Light light) {
this.light = light;
}
public void Execute() {
light.On();
}
}
// Concrete command
public class SimpleCommandLightOff : ICommand
{
private readonly Light light;
public SimpleCommandLightOff(Light light)
{
this.light = light;
}
public void Execute()
{
light.Off();
}
}
// Invoker
public class SimpleRemoteControl
{
private ICommand command;
public void SetCommand(ICommand command) {
this.command = command;
}
public void OnButtonPress() {
command.Execute();
}
// OffCommand needs to be set
public void OffButtonPress() {
command.Execute();
}
}
In the book they're stating that this is possible:
Light light = new Light();
remote.SetCommand(() => light.On());
However c# throws an error. Is this no the case when working with C#?
This does not work because in C#, lambda expressions map to delegates - a concept that does not exist in Java. Java has had a lot of these one-method interfaces for a long time before they finally introduced lambdas in Java 8. Given this and the lack of delegates, it was more or less natural to associate lambdas wit these one-method interfaces. C# / .NET, on the other hand, had delegates from the beginning and used them at many places where you would find a one-method interface in Java. Compare e.g. Observer and EventHandler.
So in a .NET API, you would consider using a delegate type like Action instead of ICommand, and then you would be able to use a lambda with it.
It should also be noted that .NET does have one-method interfaces, too. Some basic guidance about when to choose an interface or a delegate can be found at MSDN.
Matthias' answer is great, let me just add how a C# idiomatic way of declaring a command would look like:
delegate void Command();
That's it (though nowadays, you'd just use the generic Action delegate rather than defining your own). Your method would be
public void SetCommand(Command command)
{
this.command = command;
}
and invoking the command is as simple as
command();
Calling the SetCommand method can look like this:
SetCommand(() => DoSomething()); // Lambda
SetCommand(delegate () { DoSomething(); }); // Anonymous method
SetCommand(Someone.DoSomething); // Named method - Someone can be a type or an instance
As you can see, there's little point in using an interface for something a simple delegate can do. Java uses the syntax it does because it never supported delegates, and because it supports anonymous interface implementations - something C# doesn't have.
As an added bonus, delegates natively support chains - so a delegate can represent a set of delegates that are to be executed in a sequence. This is mostly used in events - another syntax helper that makes your job a little bit easier, with the handy syntax of SomeEvent += someDelegate; to register an event handler.
As an alternative, one can create an implementation of the interface that passes the calls through to lambda expressions.
public interface ICommand
{
void Execute();
int Calculate(int input);
}
public class LambdaCommand : ICommand
{
readonly Action execute;
readonly Func<int, int> calculate;
public LambdaCommand(Action execute, Func<int, int> calculate)
{
this.execute = execute;
this.calculate = calculate;
}
public void Execute() => execute();
public int Calculate() => calculate();
}
...
remote.SetCommand(new LambdaCommand(() => light.On(), _ => _));

Alternatives inline interface implementation in C#

I'd like to use inline interface implementation in C# but reading some posts like this or this I found out that it's not like Java do it.
Supposing this interface:
public interface MyListener {
void onHandleOne();
void onHandleTwo();
}
and I pass this interface as a parameter:
myMethod(MyListener listener){
//some logic
}
and when I call it I'd like to do inline imlementation like in java:
myMethod(new MyListener () {
#Override
public void onHandleOne() {
//do work
}
#Override
public void onHandleTwo() {
//do work
}
});
As an alternative I made a class that implements yhis interface and use this class to call my method:
public class MyImplementor : MyListener {
public void onHandleOne() {
//do work
}
public void onHandleTwo() {
//do work
}
}
and call my method: myMethod(new MyImplementor())
but this solutions needs a new class every time I'll call this method (for different behavior) maybe is there a way using lambda or somehow to do it like:
myMethod(new MyImplementor() =>{//handle my methods})
but this solutions needs a new class every time I'll call this method
(for different behavior) maybe is there a way using lambda or somehow
to do it like
Yes, give it a delegate parameter and pass it a lambda.
public class MyImplementor : MyListener
{
private readonly Action handle1;
private readonly Action handle2;
public MyImplementor(Action handle1, Action handle2)
{
this.handle1 = handle1;
this.handle2 = handle2;
}
public void onHandleOne()
{
handle1();
}
public void onHandleTwo()
{
handle2();
}
}
Then you can use it as
myMethod(new MyImplementor(()=>{//handle method1}, ()=>{//Handle method2});

How to define a new class that inherits from Delegate

is there anyway to do something similar to what ive got bellow.
What im trying to do is to invoke a list of delegates at a specific point in time and keep track of them, and for the sake of keeping code clean, keep the delegates to be invoked in a list of some sort.
public interface IServiceStatusDelegate
{
object DynamicInvoke(object[] args)
}
public class ServiceStatusDelegate
: Delegate, IServiceStatusDelegate
{
}
public class MyServiceStatusCheckedDelegate
: ServiceStatusDelgate
{
}
public class MyServiceStatusChangedDelegate
: ServiceStatusDelgate
{
}
public class MyClass
{
public ServiceStatusDelgate[] listOfDelegatesToInvoke;
public void InvokeRequiredDelegates()
{
foreach(ServiceStatusDelegate delegateToInvoke in this.listOfDelegatesToInvoke)
delegateToInvoke.DynamicInvoke(new object[]{this, DateTime.Now});
}
}
You don't need a list of delegates... any delegate you create in c# is going to be multicast, so all you need is any delegate, and you can combine them with +. Just invoke it and all targets will be reached. For example:
Action target = null;
...
target += Method1;
...
target += Method2;
...
if(target != null) target(); // calls Method1 and Method2
This could (although it isn't necessary for it to stand) be implemented via an event which will make the convention very obvious the caller.

Categories

Resources