Sharing C# code between Windows and Silverlight class libraries

Steve Crane picture Steve Crane · Jan 21, 2009 · Viewed 10.7k times · Source

We wrote a small Windows class library that implements extension methods for some standard types (strings initially). I placed this in a library so that any of our projects would be able to make use of it by simply referencing it and adding using XXX.Extensions.

A problem came up when we wanted to use some of these methods in Silverlight. Although all the code was compatible, a Windows library can't be referenced in Silverlight so we created a Silverlight library that had links to the same class files and put compiler directives into the classes to allow different using declarations and namespaces. This worked fine until today when I added a new class to the Windows extensions library and realised that I would have to remember to link the class into the Silverlight library too.

This isn't ideal and I wondered if anyone might have ideas for a better way of sharing extension methods and other helper code between Windows and Silverlight projects.

Answer

Maurice picture Maurice · Jan 21, 2009

You cannot set a reference from a Silverlight assembly to a regular .NET assembly but you can do so the other way round.

So create a shared Silverlight assembly and add your code to that assembly. Now you can set a reference fro both your regular .NET and you other Silverlight assembly to the shared Silverlight assembly.

The restriction is that you can only put code in there that would work on both the .NET and Silverlight CLR but that is no different from sharing code.