Is There a C#.Net Equivalent to Objective-C's Selector - c#

This is a C#.net question for Objective-C developers who also work with C#.Net
As you know, Objective-C you can parse a method name to a Selector; and the method can also belong to an outside class.
I would like to be able to use this type of method in C#.Net as it would be a lot cleaner than creating loads of Events which can become messy and hard to manage.
If this is possible, how can I achieve this? Thank you!
Example:
public class Main
{
public void MyProcess(Callback toMethod)
{
// do some fancy stuff and send it to callback object
toMethod(result);
}
}
public class Something
{
public void RunMethod()
{
MyProcess(Method1);
MyProcess(Method2);
}
private void Method1(object result)
{
// do stuff for this callback
}
private void Method2(object result)
{
// do stuff for this callback
}
}

I don't know Objective-C, but I think you want something like this:
public class Main
{
public void MyProcess(Action<object> toMethod, object result)
{
// do some fancy stuff and send it to callback object
toMethod(result);
}
}
public class Something
{
public void RunMethod()
{
object result = new object();
MyProcess(Method1, result);
MyProcess(Method2, result);
}
private void Method1(object result)
{
// do stuff for this callback
}
private void Method2(object result)
{
// do stuff for this callback
}
}

You would have to use Delegates. Based on the code in your question, you would declare a delegate:
public delegate void MethodDelegate(object result);
The signature of the process method changes to the following:
public void MyProcess(MethodDelegate toMethod)
{
// do some fancy stuff and send it to callback object
toMethod(result);
}
And then you would call process
public void RunMethod()
{
MyProcess(new MethodDelegate(Method1));
MyProcess(new MethodDelegate(Method1));
}

Related

How to declare and await an async delegate?

For some reason, despite this question coming up a lot in my googling, I can't seem to find an actual answer. Maybe I'm just using delegates wrong, I'm not sure. I'm happy for alternative ways of handling this if it's an X-Y problem.
Say I have this:
public class SomeLibrary
{
public delegate void OnSomethingHappened(EventInfo eventInfo);
public OnSomethingHappened onSomethingHappened;
public void SomeMethod()
{
// ...
// Something happened here, so we'd better trigger the event
onSomethingHappened?.Invoke(eventInfo);
// ...
}
}
public class MyCode
{
public void SomeInitialisationMethod()
{
SomeLibrary someLibrary = new SomeLibrary();
someLibrary.onSomethingHappened += SomeEventHandler;
}
private void SomeEventHandler(EventInfo eventInfo)
{
DoSyncProcessing(eventInfo);
}
}
That should all be fine (barring silly typos).
Now imagine my regular synchronous DoSyncProcessing function suddenly has to become asyncronous, like in this magic non-functional code:
public class SomeLibrary
{
public async delegate Task OnSomethingHappened(EventInfo eventInfo); // <<< IDK what I'm doing here!
public OnSomethingHappened onSomethingHappened;
public void SomeMethod()
{
// ...
// Something happened here, so we'd better trigger the event
await onSomethingHappened?.Invoke(eventInfo); // <<< IDK what I'm doing here either!
// ...
}
}
public class MyCode
{
public void SomeInitialisationMethod()
{
SomeLibrary someLibrary = new SomeLibrary();
someLibrary.onSomethingHappened += SomeEventHandler;
}
private async Task SomeEventHandler(EventInfo eventInfo)
{
await DoAsyncProcessing(eventInfo);
}
}
How can I handle that? What's the correct way to do this?
The async modifier affects the method implementation, not the signature. So change this:
public async delegate Task OnSomethingHappened(EventInfo eventInfo);
To this:
public delegate Task OnSomethingHappened(EventInfo eventInfo);
and your code will work.

Call multiple methods in a defined order

Picture a case like this:
I have a controller action (or service method) where I need to call three methods in a consecutive order, each method has a single responsibility.
public return_type MyMethod(_params_) {
// .. some code
Method_1 (...);
Method_2 (...);
Method_3 (...);
// ... some more code
}
A developer can make the mistake of calling Method_2 before Method_1, or at least we can say that nothing forces him to follow this order, or to get an exception when the order isn't followed.
Now we can call Method_2 inside Method_1, and Method_3 inside Method_2, but that doesn't seem right when each method handles a completely different responsibility.
Is there a design pattern for this situation? Or any "clean" way to handle this?
This is exactly what facade pattern do.
Try to extract the three methods to another class, and make them private. Expose a single method MyMethod that calls the other methods in the desired order. Clients should use Facade.MyMethod
More details: https://en.m.wikipedia.org/wiki/Facade_pattern
I suppose you should leave control of execution for yourself and give possibility just to set what should be executed.
public interface IMethodsExecutor
{
void Execute();
void ShouldRunMethod1();
void ShouldRunMethod2();
void ShouldRunMethod3();
}
public class MethodsExecutor: IMethodsExecutor
{
private bool _runMethod1;
private bool _runMethod2;
private bool _runMethod3;
public MethodsExecutor()
{
_runMethod1 = false;
_runMethod2 = false;
_runMethod3 = false;
}
public void ShouldRunMethod1()
{
_runMethod1 = true;
}
public void ShouldRunMethod2()
{
_runMethod2 = true;
}
public void ShouldRunMethod3()
{
_runMethod3 = true;
}
private void Method1()
{
}
private void Method2()
{
}
private void Method3()
{
}
public void Execute()
{
if (_runMethod1)
{
Method1();
}
if (_runMethod2)
{
Method2();
}
if (_runMethod3)
{
Method3();
}
}
}
So that the usage will be:
IMethodsExecutor methodsExecutor = new MethodsExecutor();
methodsExecutor.ShouldRunMethod1();
methodsExecutor.ShouldRunMethod3();
methodsExecutor.Execute();

RegisterCallback<T>(Action<T> func) , how do I store this function pointer in a class?

I'm trying to expose an API such that, I do the following
RegisterCallback<T>(Action<T> func)
{
someObj.FuncPointer = func;
}
Later on, I call func(obj) .. and the obj is of type T that the user said.
More concrete example:
var callbackRegistrar = new CBRegistrar();
callbackRegistrar.RegisterCallback<ISomeClass>(SomeFunc);
public static void SomeFunc(ISomeClass data)
{
//
}
EDIT: So I may not have been clear, so I'll add more code:
I want to make only "one" object of CBRegistrar, and connect it with many Callbacks, as such:
var callbackRegistrar = new CBRegistrar();
callbackRegistrar.RegisterCallback<ISomeClass>(SomeFunc);
callbackRegistrar.RegisterCallback<ISomeOtherClass>(SomeFunc2);
...
In fact the above code is called by reflecting over a directory of plugins.
The user puts this in their code -->
public static void SomeFunc(ISomeClass data)
{
//
}
public static void SumFunc2(ISomeOtherClass data)
{
//
}
It looks to me as if this is not possible using Generics, etc. What it looks like I might have to do is make an interface called IPlugin or something, and ask the user to do this ..
[PluginIdentifier(typeof(ISomeClass))]
public static void SomeFunc(IPluginData data)
{
var castedStuff = data as ISomeClass; // ISomeClass inherits from IPluginData
}
Seems like asking the user to do stuff that we should take care of, but anyway ...
You need a Action<T> func to store it in. There is a semantic check to make here: if someone calls RegisterCallback twice (with different values), do you want to replace the callback, or keep both ? Assuming the latter, someObj probably wants an event (indeed, this entire API could be exposed as an event), so - in the someObj class:
public event Action<T> FuncPointer;
private void InvokeCallback(T data) {
var handler = FuncPointer;
if(handler != null) handler(data);
}
Noting that RegisterCallback could be replaced entirely, still keeping the data on obj:
public event Action<T> Completed {
add { obj.FuncPointer += value; }
remove { obj.FuncPointer -= value; }
}
Then usage would be:
var callbackRegistrar = new CBRegistrar();
callbackRegistrar.Completed += SomeFunc;
Callback functions are not much used in C#. They've been replaced by events which are more elegant and easier to work with.
class CBRegistrar
{
public delegate void ActionRequiredEventHandler(object sender, ISomeClass e);
public event ActionRequiredEventHandler ActionRequired;
void RaiseActionRequiredEvent(ISomeClass parm)
{
if ( ActionRequired != null)
{
ActionRequired(this, parm);
}
}
}
class APIConsumer
{
var callbackRegistrar = new CBRegistrar();
public APIConsumer()
{
callbackRegistrar.ActionRequired += SomeFunc;
}
public void SomeFunc(object sender, ISomeClass data)
{
}
}
If you still want to use Callbacks, you can use Delegates which are more or less function pointer.
The CBRegistrar will need to be generic (if it's OK to keep a single callback type) or it can do some internal casting (if several callback types need to be registered).
public class CBRegistrar<T>
{
private Action<T> callback;
private Dictionary<Type, object> callbackMap;
public CBRegistrar()
{
this.callbackMap = new Dictionary<Type, object>();
}
public void RegisterCallback(Action<T> func)
{
this.callback = func;
}
public void RegisterGenericCallback<U>(Action<U> func)
{
this.callbackMap[typeof(U)] = func;
}
public Action<U> GetCallback<U>()
{
return this.callbackMap[typeof(U)] as Action<U>;
}
}
public interface ISomeClass
{
string GetName();
}
public class SomeClass : ISomeClass
{
public string GetName()
{
return this.GetType().Name;
}
}
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var callbackRegistrar = new CBRegistrar<ISomeClass>();
callbackRegistrar.RegisterCallback(SomeFunc);
callbackRegistrar.RegisterGenericCallback<ISomeClass>(SomeFunc);
var someone = new SomeClass();
callbackRegistrar.GetCallback<ISomeClass>()(someone);
}
public static void SomeFunc(ISomeClass data)
{
// Do something
Console.WriteLine(data.GetName());
}
}
}

implementing delegates in c#

This would be the first time I'd use delegates in c# so please bear with me. I've read a lot about them but never thought of how/why to use this construct until now.
I have some code that looks like this:
public class DoWork()
{
public MethodWorkA(List<long> TheList) {}
public void MethodWork1(parameters) {}
public void MethodWork2(parameters) {}
}
I call MethodWorkA from a method outside the class and MethodWorkA calls MethodWork 1 and 2. When I call methodA, I'd like to pass some sort of parameter so that sometimes it just does MethodWork1 and sometimes it does both MethodWork1 and MethodWork2.
So when I call the call it looks like this:
DoWork MyClass = new DoWork();
MyClass.MethodA...
Where does the delegate syntax fit in this?
Thanks.
public void MethodWorkA(Action<ParamType1, ParamType2> method) {
method(...);
}
You can call it using method group conversion:
MethodWorkA(someInstance.Method1);
You can also create a multicast delegate that calls two methods:
MethodWorkA(someInstance.Method1 + someInstance.Method2);
For what you described, you don't need delegates.
Just do something like this:
public class DoWork
{
public void MethodWorkA(List<long> theList, bool both)
{
if (both)
{
MethodWork1(1);
MethodWork2(1);
}
else MethodWork1(1);
}
public void MethodWork1(int parameters) { }
public void MethodWork2(int parameters) { }
}
If you're just experimenting with delegates, here goes:
public partial class Form1 : Form
{
Func<string, string> doThis;
public Form1()
{
InitializeComponent();
Shown += Form1_Shown;
}
void Form1_Shown(object sender, EventArgs e)
{
doThis = do1;
Text = doThis("a");
doThis = do2;
Text = doThis("a");
}
string do1(string s)
{
MessageBox.Show(s);
return "1";
}
string do2(string s)
{
MessageBox.Show(s);
return "2";
}
}
Considering that all methods are inside the same class, and you call MethodWorkA function using an instance of the class, I honestly, don't see any reason in using Action<T> or delegate, as is I understood your question.
When I call methodA, I'd like to pass some sort of parameter so that
sometimes it just does MethodWork1 and sometimes it does both
MethodWork1 and MethodWork2.
Why do not just pass a simple parameter to MethodWorkA, like
public class DoWork()
{
public enum ExecutionSequence {CallMethod1, CallMethod2, CallBoth};
public MethodWorkA(List<long> TheList, ExecutionSequence exec)
{
if(exec == ExecutionSequence.CallMethod1)
MethodWork1(..);
else if(exec == ExecutionSequence.CallMethod2)
MethodWork2(..);
else if(exec == ExecutionSequence.Both)
{
MethodWork1(..);
MethodWork2(..);
}
}
public void MethodWork1(parameters) {}
public void MethodWork2(parameters) {}
}
Much simplier and understandable for your class consumer.
If this is not what you want, please explain.
EDIT
Just to give you an idea what you can do:
Example:
public class Executor {
public void MainMethod(long parameter, IEnumerable<Action> functionsToCall) {
foreach(Action action in functionsToCall) {
action();
}
}
}
and in the code
void Main()
{
Executor exec = new Executor();
exec.MainMethod(10, new List<Action>{()=>{Console.WriteLine("Method1");},
()=>{Console.WriteLine("Method2");}
});
}
The output will be
Method1
Method2
In this way you, for example, can push into the collection only functions you want to execute. Sure, in this case, the decision logic (which functions have to be executed) is determined outside of the call.

Event driven classes in C#

I am creating an event driven class so that when I pass it a series of data, it will process and then return the value when ready.
Below is the code that I am currently using the below code however it is quite nasty and I'm not sure if can be simpler than this.
public delegate void MyEventHandler(double result);
public static MyEventHandler EventComplete;
public static void MakeSomethingHappen(double[] data)
{
ThreadPool.QueueUserWorkItem(DoSomething, data);
}
private static void DoSomething(object dblData)
{
InvokeEventComplete(AndSomethingElse((double[])dblData));
}
private static void InvokeEventComplete(double result)
{
if (EventComplete != null)
{
EventComplete(result);
}
}
public static double AndSomethingElse(double[] data)
{
//do some code
return result; //double
}
In my main class I simply hook up a method to the event like so,
MyClass.EventComplete += new MyClass.EventCompleteHandler(MyClass_EventComplete);
Here you are:
Exposed event as an actual event rather than a publicly accessible member delegate.
Eliminated extra delegate declaration and used generic delegate Action.
Eliminated extra invocation function which was simply verbose.
Used lambda expression for event registration.
Edited code is:
MyClass.EventComplete += (result) => Console.WriteLine("Result is: " + result);
public class MyClass
{
public static event Action<double> EventComplete;
public static void MakeSomethingHappen(double[] data)
{
ThreadPool.QueueUserWorkItem(DoSomething, data);
}
private static void DoSomething(object dblData)
{
var result = AndSomethingElse((double[])dblData);
if (EventComplete != null)
{
EventComplete(result);
}
}
public static double AndSomethingElse(double[] data)
{
//do some code
return result; //double
}
}
Some things to consider...
There's an EventHandler<T> where T : EventArgs in .NET, but the trade off is you end up writing a custom EventArgs to pass your double data instead of a custom delegate. Still I think that's a cleaner pattern to follow.
If you were to define your event as
public static MyEventHandler EventComplete = delegate {};
//using a no-op handler like this has implications on Garbage Collection
Does using a no-op lambda expression for initializing an event prevent GC?
you could save yourself the if(EventComplete != null) check everytime and hence make the Invoke... method redundant.
you can also simplify
MyClass.EventComplete += new MyClass.EventCompleteHandler(MyClass_EventComplete);
to
MyClass.EventComplete += MyClass_EventComplete;
Aside from that it looks fine. I presume all the static's around the code are just from working in a ConsoleApplication :-)
try using standart event pattern (thousands times used inside FCL)
// in [CompleteEventArgs.cs] file
public class CompleteEventArgs : EventArgs {
private readonly double _result;
public CompleteEventArgs(double result) {
_result = result;
}
public double Result {
get { return _result; }
}
}
// inside your class
// don't forget 'event' modifier(!) it prevents lots of illegal stuff
// like 'Complete = null' on the listener side
public static event EventHandler<CompleteEventArgs> Complete;
public static void MakeSomethingHappen(double[] data) {
ThreadPool.QueueUserWorkItem(DoSomething, data);
}
private static void DoSomething(object dblData) {
OnComplete(new CompleteEventArgs(AndSomethingElse((double[])dblData)));
}
// if you're working with a 'normal' (non-static) class
// here should be 'protected virtual' modifiers to allow inheritors
// use polymorphism to change the business logic
private static void OnComplete(CompleteEventArgs e) {
if (Complete != null)
Complete(null, e); // in 'normal' way here stands 'this' instead of 'null'
// this object (link to the sender) is pretty tricky
// and allows extra flexibility of the code on the listener side
}
public static double AndSomethingElse(double[] data) {
double result = 0;
//do some code
return result; //double
}

Categories

Resources