Multi Platform Targeting in C# using NOR
Lately I have been working on some libraries to support different platforms such as Windows, Silverlight and Windows Phone. You can read the more on MSDN at http://msdn.microsoft.com/en-us/library/ff921092(PandP.20).aspx on how to solve it.
It recommends you to use conditional symbols such as SILVERLIGHT and WINDOWS_PHONE. But what if you want to have it only in desktop version and not in Silverlight and Windows Phone. Define another symbol for DESKTOP? But this DESKTOP symbol is not standard. If your writing this application for yourself and don’t want to open source or distribute it to others, it may probably be just fine. But incase you want others to use it, it isn’t a good idea to have these non-standard symbols and tell the your users to use the one you use (feels bossy).
So I needed to solve this. Find a better way to do it. Then all of a sudden I realized that it had been somewhere back in my head all the time and I just needed to implement it.
So what is the solution?
Let's look back into one of the Computer Science knowledge – The Logic Gates, particularly the NOR gates. This is a perfect solution to solve it. I’m not going to dive deep into these gates (bing it or google it, whatever you prefer). But will rather give you a simple recap by using the truth table.
A B A OR B NOR : NOT(A OR B)
0 0 0 1
0 1 1 0
1 0 1 0
1 1 1 0
Did you see anything? Thats the answer. Try replacing A with SILVERLIGHT and B with WINDOWS_PHONE, and then it might make more sense.
The table basically is telling you to OR the two values and then apply NOT to it and you get a NOR.
In C# it would be done as
#if !(SILVERLIGHT || WINDOWS_PHONE)
// desktop (its not a silverlight or windows phone)
#endif
You could add more. !(SILVERLIGHT || WINDOW_PHONE || MONOTOUCH).
In Silverlight and Windows Phone, Microsoft doesn’t allow us to make synchronous web requests. So we need to hide synchronous functions if its in those platforms but show it in desktop versions. Using NOR gates is the perfect solution for it.
Summary of NOR gate: If any one of them is true, it evaluates it to false otherwise true.
Lesson to Learn: What you learned in Computer Science is never a waste (for those of you who complain about it). I just showed you how to apply it in a real life application. :-)