So this might be something really easy but I wanted to see if the concept of delegate would be appropriate.
I have the following method say on my main
PrintName();
GetId()
If I wanted to add "GetPhone()" Inject it if you will on my main, do I use delegate to this ?
My thought is the compiler will call main and only recognize methods on there, and has no idea if GetPhone() exist (since I just added it somewhere in the folder), the reasoning for this kind of architecture, is that I wanted to be able to just create a plug and play concept.
Thank you.
Sure. Instead of calling the functions directly, you can use a delegate and then call the delegate, like this:
delegate void GetThings();
public GetThings myDelegate;
Then, you may assign or add functions to the delegate from your "plug and play" object.
myDelegate = PrintName();
myDelegate += GetId();
myDelegate = GetPhone();
As long as the return type is the same, you can add functions to the delegate (i.e. calling the delegate once you can call more than one function).
You will need to implement checks for security, though.
Related
For a test, I want to create a generic "helper" method which will take take two arguments, the first argument is a function (or a reference to the function) and the 2nd argument is a list of objects for that function that are to be called as its parameters.
The following does this perfectly:
CallMyFunctionWithParamsPlease(new Func<int, int>(MyMethod), new object[] {1});
public static int CallMyFunctionWithParamsPlease(Delegate func, params object[] args)
{
func.DynamicInvoke(args);
return 3;
}
The thing is, this doesn't look very nice when calling it and I wish to abstract it into another method to act as syntatic sugar.
Ideally I want it to be called like this:
CallMyFunctionWithParamsPlease(myMethod, new Object[] {1});
From what I can gather, there is no elegant solution to do this in C# since I cannot pass myMethod by itself as a reference anywhere, instead I must pass it by declaring a new Func along with the return type of the method. Since I'm not using this return type anywhere, I'm not sure why it's necessary to input this information. My limited understanding is that because C# is statically typed, the compiler must know everything and things like this just aren't possible.
Is this true or not? How would I create syntatic sugar to simply pass a method to another method which can be called there without needing to invoke "new Func"? I would have thought simply passing the function as a reference pointer would allow me to do this, but I'm having difficultly doing this too. I looked into delegates, using "unsafe" with pointers, and a few other options. None of them seem to make this possible, or if they do, they didn't explain it in a manner that I could understand.
I simply want to pass a method to another method, and invoke it with a variable list of object params with variable length whereby I don't need to specify this whilst invoking it. I'm not sure if I'm trying to force C# to do something it's not meant to do here, and instead I'd be better off using a dynamically typed language to do this. The problem is I really enjoy the intellisense that the static typing of C# offers, along with the performance improvements over a language like Python. I'd just like a way to syntactically abstract away the boilerplate with my own helper methods for things like this.
UPDATE: Thanks to the comments here it seems I can do this with a lambda expression nice and elegantly. The signature can be simply changed to public static long CallMyFunctionWithParamsPlease<T>(Func<T> func)
If deferred execution is what you want simply pass a Func<TReturnType> to your method (or class). The calling method doesn't need to know how many parameters are involved.
e.g. Assuming MyMethod has a signature int MyMethod(int arg):
CallMyFunctionWithParamsPlease(() => MyMethod(1));
public static int CallMyFunctionWithParamsPlease(Func<int> func)
{
return func();
}
If MyMethod takes two parameters, it's the same call:
CallMyFunctionWithParamsPlease(() => MyMethod(1, 2));
I have to add multiple methods to the invocation list of a delegate. However, all of them have decision logic associated with them. So, there's an if block before the method gets attached to the invocation list of the delegate. Can I do this without instantiating the delegate. The code snippet looks like the following:
public delegate void SomeDelegate();
static void Method1() {}
static void Method2() {}
static void AddMethodsToInvocationList()
{
SomeDelegate someDelegate = new SomeDelegate();
if (someLogic1) someDelegate += Method1;
if (someLogic2) someDelegate += Method2;
}
Basically, I wish to be able to create an instance of the delegate without passing any methods as parameters. However I get a compiler error with "does not contain a constructor that takes 0 arguments" error, if I try and instantiate the delegate without passing any methods as parameters.
I would also be open to solving this issue a different way if someone else has a better way of doing it. However, delegates have to be used.
Thank you for any help. Much appreciated.
You can simply initialize it to null. That is the idiomatic value for a multicast delegate that doesn't have any operations added to it.
In C#, delegate behave more like a list of function pointers, so that we can call a list of methods with the same method signature via a delegate.
After the initial assignment, we can add or subtract methods from a delegate using += (additive assignment) and -= (subtractive assignment).
Say, I have two methods.
public static void Method1(string message){
// ...
}
public static void Method2(string message){
// ...
}
Now, I declare a delegate type,
public delegate void Del(string message);
If I want to execute Method1, Method2 and again Method1 in order, I can create a delegate like this.
Del delList = Method1;
delList += Method2;
delList += Method1;
Then, later in the program, If I remove Method1 from it, which occurrence of Method1 is removed? Is there any rule governing that?
I believe that the better and more readable way is to create a new delegate and add methods you want excute in order, instead of changing an existing one. I'm just curious about how -= operator is implemented for C# delegates.
If the matching performed by -= doesn't remove the one you wanted, you can call GetInvocationList(), manipulate it how you want, and make a new delegate.
However, that's only possible when you have access to the delegate. For fields, which only have operator+= and operator-= (subscribe and unsubscribe) behaviors, you'd best avoid duplicates if you care about the order of the calls.
Actually, it would probably be best to avoid duplicates altogether.
To answer the question about the specific behavior (though I still maintain that relying on it is far too confusing), operator-= uses Delegate.Remove, which is documented as:
Removes the last occurrence of the invocation list of a delegate from the invocation list of another delegate.
(The documentation for the Delegate class itself says "Managed languages use the Combine and Remove methods to implement delegate operations. Examples include the AddHandler and RemoveHandler statements in Visual Basic and the += and -= operators on delegate types in C#.")
i saw that delegate is used for custom events. as far example
delegate string FuncRef(string Val);
FuncRef fValue = GetFieldName;
fValue("hello");
what i do here just declare delegate and assign a function name to delegate and call like fValue("hello"); whenever it is required.
instead of calling the GetFieldName() through delegate i can call it directly. so i just want to know why should i use delegate to call function where as we can call function directly....what is the advantage of calling any function through delegate.
so please tell me in what kind of scenario delegate usage is required except event handling. please guide me with sample code and simulate a situation where i need to call function through delegate except event handling. please show me some real life scenario where we have to call function through delegate.
The reason to use delegates instead of calling the function directly is the same reason you do
var taxRate = 0.15;
var taxAmount = income * taxRate;
instead of
var taxAmount = income * 0.15;
In other words: using a variable to hold a reference to a callable entity (a delegate is exactly that) allows you to write code that can change its behavior depending on the parameters passed to it (the value of the delagate we 're passing in). This means more flexible code.
For examples of code that uses delegates you can look at LINQ (of course), but there's also the "delegates 101" example which is relevant in any language: filtering a list.
delegate string FuncRef(string Val);
FuncRef fValue; // class member
if (condition1)
fValue = GetFieldName1;
else if (condition2)
fValue = GetFieldName2;
else
fValue = GetFieldName3;
// Another function
fValue("hello");
Microsoft's tutorial code on C# delegates presents another interesting use case. In their example, an object called Bookstore has a method ProcessPaperbackBooks which takes a book processing delegate and applies it to each item in the class.
The cool part is that then, if you need say, a method which collects all the ISBNs of all the books in the store, you don't need to change anything in the bookstore class, but only to define a function which acts on books and pass that into the ProcessPaperbackBooks method. Delegated goodness will occur, and your new function will be applied to every item in the bookstore. Snazzy, no?
http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx
Basically any place where you want to be able to specify at runtime which function should be called.
The async BeginInvoke/EndInvoke pattern is a perfect example of this; the callback is specified via a delegate.
Shortly: You can use delegates and events members in combination to be able for example to assign an event handler to a class which does not know it before, the button class knows when it has to trigger the click event and does not know yet, internally, you will bind mybutton_Click handler to it.
Linq to objects makes extensive use of delegates:
myAnimals.Where(animal => animal.CanSwim)
the parameter supplied to the Where method ( animal => animal.CanSwim ) is a lambda expression that converts to a delegate that is applied to all elements in myAnimals.
One place I use delegates is my input handler (C#, XNA)
I have a public void OnKeyboardPress() delegate, which I bind to various functions when certain keys are pressed.
Input is a good example; rather than polling for it (i.e. every update you go 'is it ready yet?' you wait for it to call you)..such as a GUI. WPF events are delegates.
Delegates are 1st class objects. IOW you can refer to them, reassign them, etc, just like any other object.
I would like to know about the Invoke(delegate) method. I do not understand why I do not need to specify arguments. What if I need them supply..Hopefully below you better understand what I mean. Thank you
EventHandler a = new EventHandler(this.A);
Invoke(a); //where doest it take the arguments from?
a(); //does not work, missing arguments
Because Invoke is meant to be used on Windows Forms, and the pattern for events used here is well specified, the Invoke method can make an educated guess. In fact, it is documented on MSDN exactly what it does, if you try to invoke an EventHandler without parameters using Invoke:
The delegate can be an instance of EventHandler, in which case the
sender parameter will contain this control, and the event parameter
will contain EventArgs.Empty.
You can, and should, use the overload of Invoke that allows you to specifiy the parameteres of your delegate, in order to make it more explicit what is going on. Also, calling Invoke without the parameters array will only work for delegates of type EventHandler (or, of course, delegates that does not take any parameters in the first place).
I don't work with EventHandlers but I do use dynamic invocation on delegates. Normally, for me at least, the code ends up looking like this
a.Invoke(new object[] { arg0, .... argn });