Using the #if pre-processor directive to do different things for x64 builds

I'd just about finished writing an answer for a question on Stack Overflow when the poster deleted it, so I thought I'd drop the answer here instead.

The question asked was essentially:

How can I swap between two different structs depending on whether my application has been compiled as x86 or x64

Here's my answer:

You could use the #if pre-processor directive to achieve this. Here's a standalone example of using this:

using System;

namespace IfTest
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic context;
#if (BUILDARCH64)
            context = new Context64();
#else
            context = new Context();
#endif
            Console.Write(context.ToString());
        }
    }

    public struct Context
    {
    }
    public struct Context64
    {
    }
}

In your 64 bit build you'll need to set a Conditional compilation symbol, which you can do by opening the Properties for your project by double clicking on the *Properties* node in Solution Explorer, going to the *Build* tab and entering `BUILDARCH64` against the appropriate build Configuration.

I've not gone into whether doing this is a good idea or not, as there may be a better solution to the problem the asker was trying to solve, but without more detail that's hard to tell

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment