27 Aug

Sharing Code with Conditional Compilation

This is a multipart series on how to share code between .Net platforms.  All the examples will be showing how to share between Windows 8 Store applications and Windows Phone 8 application, but the techniques are useful for sharing code between any .Net/Xamarin platforms.

  1. Linked Files
  2. Conditional Compilation
  3. Partial Classes
  4. Inheritance (coming soon)
  5. Portable Class Libraries (coming soon)
  6. Universal Apps (coming soon)

What is Conditional Compilation?

Conditional Compilation tells the compiler to selectively compile code.  Many developers use these to run certain code only while in debug that they don’t want to run in production.

    //do some stuff

How do I do it?

The first step would be to link a file between two projects.  Then you can either use an existing Conditional Compilation Symbol or create your own.  For example Windows Phone 8 defines SILVERLIGHT and WINDOWS_PHONE as Conditional Compilation Symbols.  You see see what symbols have been defined by your project and even add your own by going to the Build tab in Project Properties.

To use the Conditional Compilation Symbols you just use the #if statement.  For example if you are using a namespace exists in Windows Phone, but doesn’t exist in Windows 8 you could do this:

using System.IO.IsolatedStorage;
using Windows.Storage;

The System.IO.IsolatedStorage using statement will only be compiled in the Windows Phone projects.  The Windows.Storage using statement will be compiled in all other projects.

One thought on “Sharing Code with Conditional Compilation

  1. Pingback: Linked Files | FinerCode

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>