Archive for the ‘Events’ Tag

Gambolling with Delegates   1 comment

In my previous post I explained the concept and basics of Delegates. I’ll assume that there is an understanding of Lambda Expressions. The following content’s interest is close to just academic but, understanding it is key to really take advantage of Delegates and wonders a good implementation provides.

 

Simple Start

Let’s start with this simple delegate implementation:

delegate void StringVoidDelegate(string input);

As I exposed in my previous post, this defines a method signature where a string is received as a parameter and there is no return.

Since I’m in a Console Application I’ll implement some helpers to understand what is going on using the delegate just implemented:

static int CallCount = 0;
static StringVoidDelegate CWL = input => Console.WriteLine(++CallCount + " " + input);

 

A simple usage of this method can be:

CWL("Calling Elvis");

With output:

1 Calling Elvis

 

Generic Delegate

Like any other generic capable object in .Net, delegates receive a type generically on implementation. Something like so:

delegate string ToString<T>(T obj);

 

If, for instance, we have a Person class like this:

class Person
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}

 

We can have a method compliant with ToString delegate signature like so:

ToString<Person> personToString = person => person.Name;

 

Which can be used like so:

ToString<Person> personToString = person => person.Name;
var jCleese = new Person { Name = "John Cleese", Birthday = new DateTime(1939, 10, 27) };
CWL(personToString(jCleese));

With output:

1 John Cleese

 

Stacking Delegates

Since calling a method with the assurance of its signature is so ‘OK’ we can easily stack delegates to be run consecutively, provided that the signature is the same. Same signature means all the delegates reference to de same implementation; delegates with same input and output type signatures but different implementation won’t be interoperable. Stacking and unstacking delegates is done using arithmetic ‘+’ and ‘–’ operators.

Adding adds the delegate on the right hand to the list of methods that will be called.

StringVoidDelegate Echo = input => CWL("Echo..." + input);
Echo += CWL;
Echo(personToString(jCleese));

With output:

1 Echo...John Cleese
2 John Cleese

So CWL will be run consequently after Echo with the same parameter.

Removing removes the last call to that method on the ‘stack’ if there is any. Say we have this parameter less delegate:

delegate void ParameterlessVoidDelegate();

 

This sequence:

ParameterlessVoidDelegate writeOne = () => CWL("One");
ParameterlessVoidDelegate writeTwo = () => CWL("Two");
ParameterlessVoidDelegate writeThree = () => CWL("Three");
ParameterlessVoidDelegate writeA = () => CWL("A");

ParameterlessVoidDelegate write = writeOne + writeA + writeTwo + writeA + (() => CWL("Four"));
write();
write -= writeA;
CWL("");
write();
write -= writeA;
CWL("");
write();
write -= writeA;
CWL("");
write();

Would have this output:

1 One
2 A
3 Two
4 A
5 Four
6
7 One
8 A
9 Two
10 Four
11
12 One
13 Two
14 Four
15
16 One
17 Two
18 Four

 

Composing results

When  adding delegates with a return object, all methods are ran from left to right but only the last return is accounted for, all others are discarded.

Let’s take this signature:

delegate int IntToIntDelegate(int value);

 

The following code:

IntToIntDelegate baseAddingDelegate = value =>
    {
        CWL(value.ToString());
        return value;
    };

IntToIntDelegate AddOne = value => baseAddingDelegate(value + 1);
IntToIntDelegate AddTwo = value => baseAddingDelegate(value + 2);

var addAll = AddOne + AddTwo + (value => baseAddingDelegate(value + 3));
CWL(addAll(1).ToString());

(baseAddingDelegate is just a wrapper to shorten the code)

The output is this:

1 2
2 3
3 4
4 4

 

If the intension is to have the result of the application of all methods the implementation would have to look like so:

IntToIntDelegate AddOne = value => baseAddingDelegate(value + 1);
IntToIntDelegate AddTwo = value => baseAddingDelegate(value + 2);
IntToIntDelegate AddThree = value => baseAddingDelegate(value + 3);
IntToIntDelegate progressiveSum = value => AddOne(AddTwo(AddThree(value)));
CWL(progressiveSum(1).ToString());

And the result:

1 4
2 6
3 7
4 7

 

In Event Handling

Using delegates you can easily propagate method calling without having to reference methods in each others. For instance, having this methods:

RoutedEventHandler DoOneThing = new RoutedEventHandler((s, e) => { });
void ButtonHandler(object s, EventArgs args) { }
void DoAnotherThing() { }

 

This code is very OK and might be very useful:

button.Click += DoOneThing;
DoOneThing += ButtonHandler;
button.Click += (s, e) => DoAnotherThing();

 

.Net Action and Function

Just a quick note to say that our .Net Framework friends, since .Net 2.0, were kind enough to provide some common delegate implementation and, using generics, a short way to request for a certain signature.

Their implementation is as simple as this.

 

Action

public delegate void Action();

public delegate void Action<T>(T obj);

public delegate void Action<T1, T2>(T1 arg1, T2 arg2);

public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);

//etc.

 

That can be used like so:

var a = new Action<string, int, string>((s1, i, s2) => { CWL(s1); CWL(i.ToString()); CWL(s2); });
a("One", 2, "Three");

With this output:

1 One
2 2
3 Three

 

Function

Is the same as Action but, at least, one generic type must be provide to serve as the return type. Something like so:

var f = new Func<int>(() => 3);
CWL(f().ToString());

Output:

1 3

 

 

Conclusion

Delegates that can help you simplify and encapsulate your code in an error safe way. The sky is the limit. I use them all the time to wrap generic asynchronous call handlings and stuff like that.

That’s all…hope it’s useful.

Posted 2011/02/08 by Bigsby in General

Tagged with , , , ,

Once upon a Delegate   1 comment

For the short life as a computer programmer I’ve enjoyed so far, the most miss, or not at all, understood feature of programming are delegates and, subsequently, handlers and events. I’ll try, here, to provide easily understandable way of looking at this mystery for so many ‘good’ programmers.

 

What is a delegate?

According to MSDN, a delegate is a type-safe and secure function pointer. To me this mean, a delegate is a definition of a method signature, i.e., it defines input and output parameter types for methods. Having this in mind, the following delegate definition:

delegate int StringToIntDelegate(string input);


…means that the methods compliant with this delegate, receive a string as input parameters and return an integer.

 

What is it worth?

By the first paragraph of this post, one might notice that the great majority of programmer don’t use (or so they think, as will see further down) delegates which means that they’re not essential for a computer programme to work. But, in the same direction, neither are classes and that’s not a place one wants to go. Delegates, like classes, provide strongly typed encapsulation and polymorphism whose purpose and consequences are the elimination of code redundancy and thus then probability of error and simplifies error correction.

 

An example

For instance, imagine we are implementing a class for form input field to wrap is properties and provide some validation. It would be nice to be able to generically but strongly-typed access a method that provides some validation. Bla, bla, bla…a little code might help.

The validator method would be, for our definition, a method that receives a string (that might be inserted by the user) and returns a boolean indicating if the value is valid. Something like so:

delegate bool ValidateStringDelegate(string input);

 

Having this definition at hand the implementation for an input field wrapper could look like this:

public class InputField
{
    public string Value { get; set; }
    public string Caption { get; set; }
    public ValidateStringDelegate Validator { get; set; }
    public bool IsValid { get { return Validator(Value); } }
}

 

A validator method could look like so:

bool MinimumLengthValidator(string value)
{ return value.Length > 3; }

 

An instance of InputField could look like so:

var field = new InputField(); 
field.Caption = "Property Caption";
field.Validator = new ValidateStringDelegate(MinimumLengthValidator);

 

And, at any time, there’s a safe and strongly typed way of checking if the field is valid, like:

if (field.IsValid)
    Console.WriteLine("Incorrect input!");
else
    Console.WriteLine("Input OK!");

 

 

Lambdas and delegates

I’d say lambdas and delegates are one of coding best friends ever. This happens because, as long as the delegate (the method signature, remember?) is defined a lambda expression is all that is needed to implement a method. Taking the example above, there are other shorter ways of instantiating an InputField. The following are valid and with the exact same outcome:

field.Validator = MinimumLengthValidator;

ValidateStringDelegate validator = (value) => { return value.Length > 3; };
field.Validator = validator;

field.Validator = (value) => { return value.Length > 3; };

…and, the one I would write…

field.Validator = value => value.Length > 3;

 

All these are possible because the signature of the method is established. By the time this line of code is reached, everybody knows that Validator property is to be a method that receives a string and returns a boolean.

Note that this:

var validator = (value) => { return value.Length > 3; };

is not valid and will result in compiler error because the compiler can’t tell what type value is supposed to be.

 

What about handlers and events?

As there is no chicken or egg, the event comes first.

Conceptually, and as the naming suggests, an event something that is suppose to be used (raised, so they say) when something happens. Technically it is just a delegate defined property like in the example above but whose setting is limited by the compiler. This means you can add methods to it but you can’t set it but, in my next post, I’ll explain delegate operations and the reason for this will be clear.

If will look at the customary implementation of an event in a class (or interface) it looks like so:

event HandlerType EventName;

 

Here, HandlerType is a defined delegate. In fact, our first delegate definition is just as valid as any other to use in the definition of an event:

event ValidateStringDelegate ValidateEvent;

 

This means that any handler assigned to this event must match the signature of ValidateStringDelegate.

Yes, although it is not the usual .Net approach, an event handler can have a return value. I’ll expose more on events in a future post but I’ll drop a simple implementation of the InputField class above that would be more useful in some scenarios, for instance, when the validation processing is to be called from some external object holding the InputField instance.

public class InputField
{
    public string Value { get; set; }
    public string Caption { get; set; }
    public bool IsValid { get; private set; }
    public event ValidateStringDelegate Validation;
    public void Validate()
    {
        if (null == Validation)
            IsValid = true;
        else
            IsValid = Validation(Value);
    }
}

With this implementation, a form holding the InputField would just need to call Validate method and everything else would run its course in a safe and strongly-typed manner. Here, the naming ‘event’ makes less sense conceptually but I’ll get there in a future post.

 

Conclusion

Hope this made sense and that it may help at least one programmer doing better code.

Posted 2011/02/08 by Bigsby in General

Tagged with , , , ,