C# Extension Methods and the CompilerServices.ExtensionAttribute when targeting .NET 3.5 in Silverlight
As you may know, Silverlight is a junior varsity version of WPF where the attempt is made to balance plugin size (small) with available functionality (as much as possible) which is all very understandable. One of the areas that got (IMO) less than its due (considering the amount of code required versus the benefit derived) was Routed Events.
Basically, Silverlight’s RoutedEvent Class only supports bubbling (not direct or tunneling) and Triggers only for the Loaded event. You cannot create any custom RoutedEvents and events for controls do not bubble (e.g. the Click event for ButtonBase and its inheritors).
Fortunately, the guys at IdentityMine rolled up their sleeves and provided us with Routed Events for Silverlight. I have used these before but recently got some null reference exceptions so I loaded the actual code into my project (instead of referencing the dll) in order to trace through the code and get closer to the problem (as well as learn a few things from the masters). It turned out to be WeakReferences causing the trouble which I changed and remedied my immediate problem (and hopefully did not create a future problem with any memory leaks!).
But, I came across the following compiler error which side tracked me and hopefully this post may help the next guy as I spent some time on it. The error text was:
Missing compiler required member ‘System.Runtime.CompilerServices.ExtensionAttribute..ctor’
To make a long story short, if you are targeting .Net 3.5, (you can tell by looking at your .proj file) the compiler needs to resolve System.CompilerServices.ExtensionAttribute to compile extension methods (which the Silverlight Routed Event implementation from IdentityMine uses) and that is located in v3.5 of the System.Core dll.
The brilliant workaround explained by Daniel Moth is to create a new empty code file and paste in it the following code. Seems the compiler just needs to see that class and it does not have to have the same actual implementation (or any for that matter!) as that found in the real System.Core.dll… – Cheers!
namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute : Attribute { }
}
[...] More here: C# Extension Methods and the CompilerServices.ExtensionAttribute when targeting .NET 3.5 in Silverli… [...]
[...] C# Extension Methods and the CompilerServices.ExtensionAttribute when targeting .NET 3.5 in Silverli… [...]