Archive for the ‘Delegate’ 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) };

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;

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 -= writeA;
write -= writeA;
write -= writeA;

Would have this output:

1 One
2 A
3 Two
4 A
5 Four
7 One
8 A
9 Two
10 Four
12 One
13 Two
14 Four
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 =>
        return value;

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

var addAll = AddOne + AddTwo + (value => baseAddingDelegate(value + 3));

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

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.



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



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



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


1 3




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!");
    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;
            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.



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 , , , ,

Calling methods with a time out   Leave a comment

I was implementing a communication with a device via RS232 and came across the possibility of not having any response. Just like every time one depends on someone else’s volatile response.

I looked around a bit and all I found was a little confusing and, as usual, very little generic. I put my hands on it and came up with this implementation that I now use, maybe, a little bit too much.

The Delegates

If you’re in .Net 2.0 Func<T> and Action are not yet implement. Actually, they’re just  particular delegates that are so often used that were considered for .Net 3.0 (and posterior) inclusion. Their implementation is as follows:

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



The implementation couldn’t be simpler and is based on the ability to call delegates asynchronously with BeginInvoke and WaitHandle.WaitOne method provided by IAsyncResult.AsyncWaitHandle. Note that BeginInvoke and EndInvoke are provided by the C# compiler in it’s delegate keyword. If we at the IL generated by the compiler for Func<T> it becomes clear, even if you don’t know anything about IL:

.class auto ansi sealed nested public Func<T>
    extends [mscorlib]System.MulticastDelegate
    .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed

    .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed

    .method public hidebysig newslot virtual instance !T EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed

    .method public hidebysig newslot virtual instance !T Invoke() runtime managed


If you’re wondering about System.MulticastDelegate

So the implementation goes like so for methods with a return object:

static T RunMethodWithTimeOut<T>(int millisecondsToWait, T timeoutResult, Func<T> method)
    var asyncResult = method.BeginInvoke(null, null);
    if (!asyncResult.AsyncWaitHandle.WaitOne(millisecondsToWait))
        return timeoutResult;
    return method.EndInvoke(asyncResult);


And with void return, a boolean is returned indicating if the method ended which might be handy:

static bool RunMethodWithTimeOut(int millisecondsToWait, Action method)
    var asyncResult = method.BeginInvoke(null, null);
    if (!asyncResult.AsyncWaitHandle.WaitOne(millisecondsToWait))
        return false;
    return true;



For testing I implemented these two methods that use both implementations of RunMethodWithTimeout:

static string TestStringTimeout(int timeoutSeconds, int methodSeconds, 
							string timeoutResult, string methodResult)
    return RunMethodWithTimeOut<string>(timeoutSeconds * 1000, timeoutResult,
			() => { Thread.Sleep(methodSeconds * 1000); return methodResult; });

static bool TestVoidMethod(int timeoutSeconds, int methodSeconds)
    return RunMethodWithTimeOut(timeoutSeconds * 1000, 
			() => Thread.Sleep(methodSeconds * 1000));


And run them in a console application testing all who-arrives-first scenarios:

static void Main(string[] args)
    Console.WriteLine(TestStringTimeout(1, 2, "Timed out!", "++Success"));
    Console.WriteLine(TestStringTimeout(2, 1, "Timed out!", "++Success"));
    Console.WriteLine(TestStringTimeout(1, 1, "Timed out!", "++Success"));
    Console.WriteLine(TestVoidMethod(1, 2) ? "++Success" : "Timed out!");
    Console.WriteLine(TestVoidMethod(2, 1) ? "++Success" : "Timed out!");
    Console.WriteLine(TestVoidMethod(1, 1) ? "++Success" : "Timed out!");


That’s wrap.


Heads up! Update

I was happily using this method when I started to run into some troubles. Now, it is quite obvious but I missed this very important issue: the method whose result is dismissed because it timed out has to be stopped.

In these cases, an overload providing and end method is most useful. Something like so:

static T RunMethodWithTimeOut<T>(int millisecondsToWait, T timeoutResult, Func<T> method, Action end)
    var asyncResult = method.BeginInvoke(null, null);
    if (!asyncResult.AsyncWaitHandle.WaitOne(millisecondsToWait))
        return timeoutResult;
    return method.EndInvoke(asyncResult);


And invoking would look something like this:

var isTimedOut = false;
var result = RunMethodWithTimeOut<string>(1000, "TimedOut",
    () =>
        string successResult;
        do successResult = DoSomeProcessingThatMightNeverBeGood();
        while (null != successResult && !isTimedOut);
        return successResult;
    () => { isTimedOut = true; });