ObservableDeveloper - Leonid Sorokin's Blog

.NET, Silverlight, ASP.NET, Web Services, SQL Server, Cloud Computing, and much more...

About the author

I am a .NET Software Developer, Consultant, and Trainer from Toronto, Canada specializing in web development with Rich Internet Applications on the Microsoft development tool chain.

My Photo

Microsoft Certified Professional Developer

Reusing .NET Framework 3.5 code in Silverlight 3

Over the past couple of days, I have been trying to port pieces of .NET code that I have written to the Silverlight runtime.

First, I have to clarify what I mean by reusing. In this case, reusing simply means using C# code from the full .NET Framework verbatim in Silverlight.

I want to simply be able to add a file as a link in Visual Studio 2008 – this will enable me to re-use .NET Framework code in Silverlight hassle-free.

Here are a few suggestions that you may find useful, if, for example, the code that you are re-using in Silverlight is not compiling. All of the suggestions below make it necessary for you to go back to your “server” code (i.e. .NET Framework code), and alter it so that it compiles under Silverlight.

  1. Make the problematic class a partial class. As such, you can port only a part of that class and leave out that portion of the class that would not be necessary in Silverlight.
  2. Use extension methods. Extension methods allow you to easily re-use bits of code while maintaining clarity. For example, I was using a .NET Framework method ConvertAll that was missing in Silverlight. I decided to create an extension method with slightly different parameters than the .NET Framework-based method, and changed my “server” code to use the extension method.
  3. Use partial methods. Although I rarely use partial methods, you can definitely use them when reusing code. However, many methods cannot be made partial (such as if a method does not return void, or if it has the override keyword. Because of these severe restrictions, partial methods are not always appropriate.
  4. Finally, if all else fails, you can use the good ol’ #IF…#ENDIF preprocessor directive to tell the compiler to include/exclude source code at compile time. For example, you can set the conditional compilation symbol on the “server” – so that when compiling under Silverlight, the bits of code that are only server bound will not get compiled.

Hope this helps.


Permalink | Comments (0) | Post RSSRSS comment feed