[Journal - Boxing In The Dark]

Boxing In The Dark

Saturday, September 15, 2007

Since I've addressed various aspects of .NET delegates at this site in the past, I thought I'd share another piece of trivia, if only for the sake of completeness:

If you point a delegate to an instance method of a value type, then that value gets boxed. The boxed object can then only be retrieved through the Target property of the delegate.

This is not an issue in properly designed code: Structs are used when the focus is on simple data, not complex data structures and loads of tricky interactions. Normally, there's no reason for a delegate to point to any instance unless the data in that instance is either used or changed by the call. Since value types follow value, aka copy, semantics, it's hard to know which data the call will operate on. This means that using a value type instance method for a delegate is a bad idea to begin with, so the implicit boxing doesn't really make things worse.