Invoke delegate without arguments? - c#

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 });

Related

How to create hooks in c# using delegates

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.

How to get the arguments from an Action?

I have a method that accepts an Action with a signature like:
public void DoSomething(Action code);
then I would call this method like:
DoSomething(()=> CallSomething("A","B","C");
In the DoSomething method, how can I get the argument values?
Another thing to consider is that CallSomething can potentially have optional parameters, meaning I can't just change the signature of DoSomething to -> Expression<Action>
All I need to do is get the argument values, I'm interested in any method that can work.
I've already tried to create a new method which accepts Expression<Action> then pass the Action through (From DoSomething), but the arguments weren't populated.
Any suggestions welcome.
The point is you don't want to.
Your method accepts an Action delegate. It's saying "I only want something to call that has no arguments and returns no value".
If you need to pass arguments to the function, either use a different delegate, or pass them as arguments directly.
Think about this without the lambda. You have an interface that has a single method, Act that takes no arguments and returns no value.
DoSomething(IMyInterface myInterface)
{
myInterface.Act(); // How do I get the arguments of some method that `Act` calls?
}
Does this make any sense whatsoever? Would you expect to be able to disassemble the whole instance that's passed in myInterface, find its Act method, go through all of the methods that are called from there and intercept their arguments? Delegates are little but a single-method interface with a bit of state carried over.
If you need the arguments, make them part of the public interface. Otherwise, your abstraction has no meaning whatsoever, and you shouldn't be using it. Nobody is forcing you to use lambdas, and nobody is forcing you to pass a single lambda and no arguments, and nobody is forcing you to use Action in particular. They are all simple tools - if they don't fit your task, don't use them.
To answer your question more directly: you get the arguments as any other arguments. The problem is that your action has no arguments.

Passing textbox instance to method group

I made a method to loop and clear all textbox controls in my form.
Controls.OfType<TextBox>()
.ToList()
.ForEach(tb => tb.Clear());
This works just fine, but I figured that since the first argument passed to any instance method is always a reference to the instance that I should be able to write it like this
Controls.OfType<TextBox>()
.ToList()
.ForEach(TextBox.Clear);
Unfortunately that doesn't actually work, and I don't quite understand why..
It would work if TextBox.Clear was a static method with a TextBox parameter; but instead, it's an instance method with no parameters, so the compiler can't automatically transform it to an Action<TextBox>.
Note that the CLR does support open-instance delegates (you can create one with the Delegate.CreateDelegate method), but the C# language doesn't support it.
Here's how to create an open-instance delegate that will invoke TextBox.Clear on its argument:
var action = (Action<TextBox>)Delegate.CreateDelegate(
typeof(Action<TextBox>),
null,
typeof(TextBox).GetMethod("Clear"));
The this parameter is implicit, not explicit. Foreach is expecting a method with an explicit parameter, not an implicit one.
As for why the C# language team didn't implement this feature, you'll have to ask them. They of course could have designed the language to support this, if they wanted to. There's no real point in us speculating as to why they didn't.

Generic Callbacks in C#

I want to write a wrapper for the System.Web.Caching.Cache, which handles my cache requests.
I need a method, which can invoke a callback method, if the cache entry doesn't exist. The problem is: I dont know how many params the callback method has:
public T Get<T, TCallback>(string key, TCallback func) where TCallback : Func<T>
{
// check cachekey, do sth
T result = func.Invoke();
return result;
}
With this implementation it's possible to give a callback without params. But what if I have some?
Thanks,
trial
This method should only accept the parameters that this implementation wants to send to a given function. If it has no information that would be relevant to such a callback then it should simply require a parameter-less delegate. If it has parameters that will be needed for some, but won't be needed for others, it should provide them in all cases, using a single delegate.
It then becomes the responsibility of the caller to match the function that they want to call with the signature of the delegate. If they want to fix values for some function that has parameters your callback doesn't have, or if they want to call a function with less parameters, etc. it is their responsibility to make the "conversion", rather than this method's responsibility to deal with a delegate with an unknown signature.
The use of lambdas makes "converting" functions very easy; much easier than the alternative. To fix a value for a parameter when your callback doesn't have one, you can close over the variable:
int value = 5;
Get("key", () => SomeMethod(value));
You can also use a lambda to ignore a parameter:
Get("key", someParameterToIgnore => AnotherMethod());
1) You can use dynamic or Dictionary as parameter of your callback. Put in Dictionary or dynamic string value - like CallbackType.
Its bad because you lost static type analysing, but it possible.
2)It may be useful: Ellipsis notation in C#?

The usage of delegate

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.

Categories