How do delegates work in c# behind the scenes and how can they be used efficiently?
EDIT: I know how they work on the surface(they are basically function pointers and allow callback methods with certain signatures to be invoked using their address). What I need to know is how the CLR actually implements them internally. What exactly happens behind the scenes when you define a delegate and when you invoke a callback method using the delegate object?
Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.
delegate \DEL-uh-gayt\ verb. 1 : to entrust to another. 2 : to appoint as one's representative. 3 : to assign responsibility or authority.
A delegate is a type safe function pointer. That is, they hold reference(Pointer) to a function. The signature of the delegate must match the signature of the function, the delegate points to, otherwise you get a compiler error. This is the reason delegates are called as type safe function pointers.
Re efficiency - it isn't clear what you mean, but they can be used to achieve efficiency, by avoiding expensive reflection. For example, by using Delegate.CreateDelegate
to create a (typed) pre-checked delegate to a dynamic/looked-up method, rather than using the (slower) MethodInfo.Invoke
.
For a trivial example (accessing the static T Parse(string)
pattern for a type), see below. Note that it only uses reflection once (per type), rather than lots of times. This should out-perform either reflection or typical TypeConverter
usage:
using System;
using System.Reflection;
static class Program { // formatted for space
static void Main() {
// do this in a loop to see benefit...
int i = Test<int>.Parse("123");
float f = Test<float>.Parse("123.45");
}
}
static class Test<T> {
public static T Parse(string text) { return parse(text); }
static readonly Func<string, T> parse;
static Test() {
try {
MethodInfo method = typeof(T).GetMethod("Parse",
BindingFlags.Public | BindingFlags.Static,
null, new Type[] { typeof(string) }, null);
parse = (Func<string, T>) Delegate.CreateDelegate(
typeof(Func<string, T>), method);
} catch (Exception ex) {
string msg = ex.Message;
parse = delegate { throw new NotSupportedException(msg); };
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With