The usage of delegate - 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.

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.

Delegates, Actions, Events, Lambda expression and MVVM

I have spent few days trying to understand WPF and MVVM. It is going very slowly mostly because I have some lack of knowledge in terms of events and stuff. Here bellow I will try to explain my understanding of all this things:
Method – this one is simple and I don't think it needs any explanation. Basic ingredient in any program.
Delegate – the way I see it is pointer on method. I can think of only few applications where I would want to use it over a method.
Action – that one is even trickier. Information I have managed to find say that it is a delegate that doesn't return value... so is it just pointer on void method? I don't see point of that
Event – this one I don't get at all. It was being explained with delegate and I didn't understand how does it work and what is it for. Note I was using events writing winforms applications but it was just choosing desired event from the list.
Event handler – even more unclear.
Lambda expression – also yet another way of using method. Again I understand it doesn't return anything, I can pass some argument in it, but still aint much different from void method. I have seen some applications like when using LINQ but I still don't understand how it works.
I would like to start by saying that I understand basic construct of MVVM, what is doing what and so on. Issue I have is that I don't understand some of the code, how does it work and therefore I can't write anything actually on my own. I will be using some tutorials as example so here it goes:
S1: https://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030
S2: http://social.technet.microsoft.com/wiki/contents/articles/18199.event-handling-in-an-mvvm-wpf-application.aspx
What I am expecting from you guys is some guidance or explanation how can I approach and understand those thinks to make them at least a little less scary for me. Here I will place some examples that will hopefully show you what kind of problems I have.
1) First one comes from S1 from well known RelayCommand class:
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
I know what it is suppose to do (name speaks for itself). But I don't understand how this thing works? How it knows when to make something executable and when not. What are exactly those add and remove “commands”? I tried to read about it but it didn't help.
2) Another example form S1:
#region CloseCommand
/// <summary>
/// Returns the command that, when invoked, attempts
/// to remove this workspace from the user interface.
/// </summary>
public ICommand CloseCommand
{
get
{
if (_closeCommand == null)
_closeCommand = new RelayCommand(param => this.OnRequestClose());
return _closeCommand;
}
}
#endregion // CloseCommand
#region RequestClose [event]
/// <summary>
/// Raised when this workspace should be removed from the UI.
/// </summary>
public event EventHandler RequestClose;
void OnRequestClose()
{
EventHandler handler = this.RequestClose;
if (handler != null)
handler(this, EventArgs.Empty);
}
#endregion // RequestClose [event]
Again I know what it is suppose to do, I even understand what is basically happening here but I don't see where this “thing” is actually doing something. OnRequestClose() is just creating handler that in my eyes doesn't do anything to close whatever it is suppose to close. Problem is that if I even don't see where command is executed how can I write my own commands.
3) I think this will be last example, this time from S2:
public ViewModel()
{
_clickCommand = new DelegateCommand<string>(
(s) => { /* perform some action */ }, //Execute
(s) => { return !string.IsNullOrEmpty(_input); } //CanExecute
);
}
Here problem is pretty simple. It is creating command using RelayCommand ctor (or at least it's version in this project, here called “DelegateCommand”). I don't understand those (s) and use of lambda. What is it for?
Of course that isn't everything I have problem with but I think that will give idea what is my problem to anyone willing to help. I tried to explain my problem as best as I can and I would really appreciate any help or guidance. Maybe I am expecting to much from myself but I feel like I need to know all that stuff in order to write anything serious.
Anyway thank you all in advance for any help.
A long answer for your broad question.
Let me dig into Events and EventHandler first using a simple approach
Suppose there is a big function organized in your city which will host many famous people from your country.
Let's consider three guest's for this example
Guest one is a person who is unknown by other guests
Guest two is a famous person from your area and very few people know
Guest three is very famous across your country
Consider the following assumptions
Nobody is waiting for guest one (0 EventHandler)
There are four
people who are waiting for guest two (4 EventHandler's each person is
an event handler waiting to greet)
There are three security personnel and 10 guests (out of which one
person is also waiting for guest 2) waiting for guest 3 (13
EventHandler's)
Scenario 1
When guest one arrives at the venue (Event raised) nothing happens
Scenario 2
When guest two arrives at the venue (Event raised) the four people move towards him/her and give greetings
Scenario 3
When guest three arrives (Event) you will see security forces providing cover and ten people move towards him/her and give greetings
Simple points to be observed
1. Event is just a notification that something has happened (like a delegate with a method signature)
2. EventHandler is an action as to what happens when a specific event has happened ( a method which implements the method signature defined
by the delegate)
3. One event can have many eventhandlers (e.g.. scenario 2,3). Hence the syntax += in the below code sample
The below code will answer some of your basic questions
class Program
{
static void Main(string[] args)
{
var test = new Example();
Console.ReadLine();
}
}
class Example
{
//This is the event definition
delegate void ActionDelegate(string input1, string input2);
// Two event handler which implements the signature of the event
void ActionMethod(string a, string b)
{
Console.WriteLine(a + " " + b);
}
void ActionMethod2(string c, string d)
{
Console.WriteLine("Wow one more function called with parameter {0} and {1}", c, d);
}
delegate Tuple<string, string> LamdaDelegate(string input1, string input2);
public Example()
{
//Did not declare any delegate member variable explicitly.
//Clean and easy to understand
Action<string, string> action = ActionMethod;
// Had to define the delegate with method signature explicitly before using it
ActionDelegate actionDelegate = ActionMethod;
actionDelegate += ActionMethod2; // Attaching more event handlers to the event
//The below lambda expression implicitly means that it will take two inputs each of type string
// and does not return anything.
//The type information is implicitly derived from the method signature of the delegate
actionDelegate += (a, b) => Console.WriteLine("Called using lambda expression");
//Below is a Lambda expression in which s and e each is of type string
//Since the return type of the delegate is Tuple<string,string> the same is returned by the expression
//Lambda expression is using a delegate without defining a delegate explicitly.
LamdaDelegate myTuple = (s, e) => { return Tuple.Create(s, e); };
//The above Lambda can be rewritten as
myTuple += delegate (string a, string b) { return Tuple.Create(a, b); };
//Invoking the event handlers. The event handlers are executed automatically when ever the event occurs
action("Hi", "called from action");
actionDelegate("Hi", "called using explicitly defined delegate");
}
}
Why should we use delegates?
In the above example you saw that the ActionMethod is used by two different delegates(read Event).
Without delegates the above example would be dirty and unreadable.
The above example also shows Action which simplifies the need to define delegates explicitly.
Now comming to Commands
In MVVM the traditional event is replaced by Command and the event parameters (read delegate method signature) is replaced by CommandParameter
In your 3rd question the DelegateCommand has a type parameter which is string. So the (s) you see is a variable which stores the input string sent from UI. Now it is upto you to decide if you want to use the input (s) or ignore it all together. In the CanExecute part you can see that even when the input (s) is passed it has ignored it and uses the other member variable _input.
The 2nd question an event RequestClose is defined which is attached an event handler in Figure 7 of the link. Also observe that in the same figure the MenuItem is bound to the CloseCommand in the ViewModel.
So now when you click on the MenuItem the CloseCommand is invoked and it then calls the function OnRequestClose. The first thing this function checks is that is there anyone interested(read listening) in the event RequestClose which the MainWindow is listening and hence calls the window.Close()
For more clarification please do let me know.
EDIT
The code example above was just for Action<T> and delegate.
In layman terms let me put it this way
If I want to do something based on some external action I would use Event . I will just define an event and wire it up to an EventHandler and just wait for the action to occur. (In the example above I don't know when will the guest arrive but whenever they do arrive the EventHandler will respond automatically)
On the other hand I will use delegate if I want to call single/multiple functions simultaneously based on some internal condition defined in the code. In the code example above you can see that I had to invoke the delegate manually.
Please ignore the Tuple as it is just a return value with no actual importance.
EDIT 2
The scenario (_) or (s) is similar. Both mean that you will get a parameter as an input but in the first scenario the developer is trying to say that this parameter will not be used or ignored while in the (s) they intend to use it
You can't use just () as this means that the lambda expression does not contain any input parameter which is wrong since the definition says that it will receive a string as an input.
1. Delegate
the way I see it is pointer on method
Correct. However since C# is strongly typed, you need to define, what parameters and return type must the method have. This is what delegates are.
I can think of only few applications where I would want to use it over
a method.
This is not about method vs deledate. When you need to pass method as a parameter, then the parameter is defined using delegate.
2. Action
Action is concrete type of delegate. While delegate can refer to any method, Action says, that it is parameterless method with return type void. Action<string> means that parameter is of type string. Action<string, int> means that the method's first parameter must be of type string and second of type int.
Another concrete example of delegate is Func delegate. Func<bool> means that the method does not have parameters and returns bool. Func<string, bool> means that there is one input parameter of type string and it returns bool.
EventHandler is just another delegate, that represents method with void return type and two input parameters: object and EventArgs
3. Event
just think about Button.Click event. The programmers at microsoft that worked on Button class had to provide a way how to notify your program, that button was clicked. So they defined an event and you can handle the event by providing a method that will execute when the event occurs. The method is called eventhandler.
4. EventHandler
is either used as common name for methods that are assinged to events or it is concrete delegate that defines input and output parameters or it is used as.
e.g: Button.Click += DoSomehing; Click is an event. Method DoSomething is and eventhandler. Is must return void and have two input parameters of type object and EventArgs, because when you look at the definition of click event, you can see concrete delegate type which is EventHandler (or RoutedEventHandler - just another delegate used in WPF in some events).
5. Lambda expression
is very simple. Lambda expression is just another syntax to write a method. Compiler translates lambdas to methods anyway. Lambdas are just syntactic sugar.
following method and lambda are equal
bool IsGreaterThan5(int number)
{
return number > 5;
}
var isGreaterThan5 = new Func<int, bool>(number => number > 5);
for example, if you have an array of integers, then you can use Where linq extention method to filter the array. Intelli sense tells you, that the parameter of Where method is Func<int, bool>. Therefore you need to pass method that takes one parameter of type int and returns bool.
int[] numbers = new []{ 1, 2, 3 4, 5, 6, 7 };
var filteredNumbers = numbers.Where(IsGreaterThan5); //method IsGreaterThan5 is defined in previus example
//just another syntax:
var filteredNumbers = numbers.Where(number => number > 5);
//just another syntax:
var filteredNumbers = numbers.Where(new Func<int, bool>(number => number > 5));
//just another syntax:
Func<int, bool> isGreaterThan5 = i => i > 5; //it does not matter how you name the input parameter
var filteredNumbers = numbers.Where(isGreaterThan5);

Passing anonymous/lambda functions to void delegates with no parameters? [C#]

I've been exploring C# delegates and anonymous/lambda functions, and I have some questions about how they interact. From what I understand, a simple delegate object can have predefined return and parameter types, and any named function with those same return/parameter types can be assigned to the delegate.
In my case, however, I've been working on a game where the Player can enqueue multiple Commands into their commandList. At some point after being added to the command list, commands are eventually executed by the player..
I started implementing this by creating specific subclasses for each command (AttackCommand, HealCommand, etc.), but then later found that to be tedious when it came to prototyping a variety of new commands. I thought it would be cool, for testing purposes, to create a CustomCommand class with a member delegate so that I could define and pass functions anonymously and quickly iterate on new game design ideas.
public class CustomCommand : Command {
public delegate void CommandDelegate();
private CommandDelegate func;
public CustomCommand( CommandDelegate del ){
func = del;
}
public Execute(){
func();
}
}
Then Player has a method that defines an anonymous function and uses it to construct a CustomCommand. However, something that confuses me a little bit is the fact that the arguments of this method seem to be able to be stored in the CustomCommand's delegate:
//inside Player class..
//command to steal gold from a target!
public CreateCustomCommand( Player targetPlayer ){
CustomCommand.CommandDelegate anonCommand = delegate()
{
//Steals up to amount passed..
int goldToSteal = targetPlayer.StealGold(25);
gold += goldToSteal;
};
CustomCommand newCommand = new CustomCommand( anonCommand );
commandList.Enqueue( newCommand );
}
//Command is automatically executed later..
I've tried this code, and not only does it compile, but it also works; money is stolen from the target and added to the source player. I'm happy that it works, but it's a little bit unsettling that I'm not sure what exactly is going on behind the scenes..
Here's what I'm having a hard time understanding:
Inside the CreateCustomCommand method (of Player), gold is in scope as it is a member of the Player class, and targetPlayer is in scope because it's a parameter.. But how is it that these things can be wrapped up in a anonymous function and passed to a void, parameterless delegate that's inside another object and still work? What's happening here? Does the creation of an anonymous function store references to all of the objects that it contains?
This seems extremely flexible compared to assigning named functions to delegates with matching return/parameter types, but are there any major drawbacks or pitfalls? Also, is this technique related to (or part of) any particular design pattern or programming methodology?
If I understand this correctly, this works because anonymous functions make use of closures. Closures are blocks of code that can capture (See: Variable Scope In Lambda Expressions) the variable environments in which they were made.
So, because the CreateCustomCommand method defined an anonymous function (a closure), the anonymous function captured and maintained access to the variables that were in scope of CreateCustomCommand.
Thanks to #HansPassant for pointing me in the right direction!

Can C# Delegates work this way?

I'm trying to use delegates to cut down on my code in this project.
I have 4 DropDownLists in my asp.net page. In my codebehind file I'm binding them to different business object calls with data. Right now I have the following code:
DeptList.DataSource = bl.getAcademicDepts();
DeptList.DataBind();
TermList.DataSource = bl.getTerms();
TermList.DataBind();
InstructorList.DataSource = bl.getInstructors();
InstructorList.DataBind();
EEList.DataSource = bl.getEE();
EEList.DataBind();
This seems really repetitive so I decided to make a function as a shortcut
private void SourceAndBind(DropDownList d, <business layer method call>)
{
d.DataSource = <businesslayer method call>();
d.DataBind();
}
Then my first block of code simply becomes
SourceAndBind(DeptList, bl.getAcademicDepts());
SourceAndBind(TermList, bl.getTerms());
SourceAndBind(InstructorList, bl.getInstructors());
SourceAndBind(EEList, bl.getEE());
However, I don't know what to put for the second parameter. Each one of the business layer calls takes no parameters, but they each return objects of different types. I tried using delegates but I couldn't figure out how to create one without a defined return type or no parameters. Is it possible to achieve what I want with c#? I know that works in python which is where I'm coming from.
You don't need delegates to do this. Just declare the second parameter as object.
// Takes drop down list and data to assign to 'data source'
private void SourceAndBind(DropDownList d, object data) {
d.DataSource = data;
d.DataBind();
}
// Call methods from bussiness layer and bind results
SourceAndBind(DeptList, bl.getAcademicDepts());
SourceAndBind(TermList, bl.getTerms());
SourceAndBind(InstructorList, bl.getInstructors());
SourceAndBind(EEList, bl.getEE());
You could use delegates too. However, since you're only calling the method once, you can call the bussiness layer method to get the data and then pass the result to SourceAndBind. (Delegates would be useful for example if you wanted to choose one of several ways of loading the data, or if you wanted to delay loading until some later point).
Well, Func<object> would be a very general way of doing that. That's "a function with no parameters that returns an object". Any parameterless function returning a reference type should be convertible to that delegate type. However, your "usage" code wouldn't be quite right as it. It would be:
SourceAndBind(DeptList, bl.getAcademicDepts);
SourceAndBind(TermList, bl.getTerms);
SourceAndBind(InstructorList, bl.getInstructors);
SourceAndBind(EEList, bl.getEE);
Note the lack of brackets, which means these are method groups rather than method calls. (To follow .NET naming conventions I'd suggest renaming your methods to start with capital letters, btw.)
That's appropriate if you only want to call the method conditionally. As Tomas says though, you don't need to use delegates here. If you're happy for SourceAndBind to only get called after you've called the method, you can definitely just perform the method call in the argument and pass the result as object.
private void SourceAndBind(DropDownList d, Func<IEnumerable<object>> businessLayerMethod)
{
d.DataSource = businessLayerMethod();
d.DataBind();
}
IEnumerable<object> where object is your datatype.

Passing a stored procedure call from a LINQ data context to another method. C#

I feel the answer to this may lie with delegates, but I am having a hard time grasping the concept of delegates. The main problem is that every explanation and example of delegates I have ever read are always round about ways of doing something you could accomplish without delegates so to me it does not teach me anything. I learn best by seeing real world examples.
Now that that is out of the way, here is what I want to accomplish. I have a Data Context (.dbml) with numerous stored procedures. I also have mutliple situations where I am using the exact same 20 lines of code to update one column in a table, but the only difference other than using a different datagrid, is the stored procedure being called. In an effort of reducing the amount of code used, I was hoping for a way to pass the stored procedure call from the data context object as a parameter. That way I can move all that code to one reusable function. Is this even possible? I am using Visual Studio 2008 and C#.
Thanks for any guidance.
While I can't help you with the sql / stored proc side of things, I can try explain delegates, at least from the C# point of view.
While normally you declare functions as being part of a class (and hence they are strongly attached to the class), sometimes you want to put them in a variable. Once you do this, you can then pass it around, much like you would with any other variable.
So we know that a string is the kind of variable that you stick text into. Following that, a delegate is the kind of variable that you stick functions into. This however is very confusing, as C# isn't consistent or clear with how it names things in your code. Observe:
public void WriteText() {
Console.WriteLine("Hello");
}
...
Action x = WriteText;
x(); // will invoke the WriteText function
Note we're using "Action" where logic would imply the code should read delegate x = WriteText. The reason we need this extra mess is because "delegate" itself is like System.Object. It doesn't contain any information, and it's kind of the "base class" behind everything. If we actually want to use one, we have to attach some Type information. This is where Action comes in. The definition of Action is as follows:
public delegate void Action();
What this code says is "we're declaring a new delegate called Action, and it takes no parameters and returns void". Thereafter if you have any functions which also take no parameters and return void, you put them in variables of type Action.
Now, you can stick a normal function into a delegate, but you can also stick an "anonymous" function into a delegate. An "anonymous" function is something that you declare inline, so rather than attaching the already-declared WriteText function, we could build a new one up in the middle of our code like this:
Action x = () => { Console.WriteLine("Hello"); };
x(); // invoke our anonymous function.
What this is doing is using the C# "lambda syntax" to declare a new anonymous function. The code that runs as part of the function (when we invoke it) is the Console.WriteLine.
SO
To put it all together, you could have a "SaveData" function, and pass it a delegate. It could do it's 20 lines of table building, then pass that table to the delegate, and the delegate could invoke the appropriate stored-proc. Here's a simple example:
public void SaveData(Action<Table> saveFunc){
var t = new Table();
... 20 lines of code which put stuff into t ...
saveFunc(t);
}
SaveData( t => StoredProc1.Invoke(t) ); // save using StoredProc1
SaveData( t => StoredProc37.Invoke(t) ); // save using StoredProc37
SO
Having said ALL OF THAT. This isn't how I'd actually solve the problem. Rather than passing the delegate into your savedata function, it would make more sense to have your SaveData function simply return the table, and then you could then invoke the appropriate StoredProc without needing delegates at all

Categories