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?
Best Answer
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 typicalTypeConverter
usage: