Sunday, 17 February 2008

Code Reuse (in Silverlight Today)

Following on from my previous posting where I ask for some support in Visual Studio for Code Reuse with Silverlight projects. Daniel Moth (one of Microsoft UK's evangelists) kindly posted a current workaround suggestion in the comments on a workaround that you can use today to reuse code between Silverlight and Non Silverlight projects.

You can read in more detail about Daniel's workaround in his MSDN article that he did last year (which is Compact Framework related).

They key thing that Daniel is suggesting, is that to reuse common code in both Silverlight and Non Silverlight projects, you should do the following.

1) Create two versions of the assembly (one silverlight and one regular .NET Framework)
2) Create the class in the regular class library as normal
3) In the silverlight version of the project -> Select Add Existing Item -> and within the Open File Dialog, select the "Add as Link" option

Daniel also suggests that you can use the following techinques to handle the differences between framework implementations

  • Conditional Compilation

  • Extension Methods

  • Partial Types

This is some really great workarounds from Daniel on how to getting around some of these issues today and promotes a great way for you to be able to reuse code already (rather than cutting and pasting).

I still have one major concern, which is that there is still quite alot of overhead to reusing code. You still have to maintain two versions of each assembly (3 if you wish to reuse between silverlight, compact framework, and full .NET Framework), you as a developer need to constantly check your code compiles against the 2 platforms, you need to think about your compiler directives etc.

Although this is a great workaround (and I recommend you use these techniques), I still think that Visual Studio should provide us this support, using a technique such as the virtual assembly reference (that i suggested in my previous post).

Thanks again to Daniel for this workaround and I believe he will be writing up a Silverlight version of his article (which I look forward to), however there should be enough information here to get you going with code reuse between Silverlight and Non Silverlight projects today.

No comments: