Migration from 32bit to 64bit Projects in .NET

In this blog post, I am going to explain the solution for a few issues that I had working with 32bit and 64 bit Operating systems and what we should do to create applications that would work without any code changes in any environments.
If you go to project properties and then navigate to Build tab, you will see a dropdown for Platform target. By default, this value is set to "Any CPU". You can change it to specifically target x86 (32bit) and x64 (64bit) environments. 
So, first I created 3 projects. Lets call them -
  • A - Console app. This will be the startup project and hence the calling assembly.
  • B - Class library. A just calls a method in a class in B.
  • C - Class library. B just calls a method in a class in C.
So when we run the app, it will work on both 32bit and 64bit OSs because by default the target was set to "Any CPU". So if all this works then why this blog?
In this example, we had the code for all three DLLs. Sometimes, our code refers to other DLLs, on which we have no control. Recently in one of the projects I was working, we were referencing SQL CE v3.0 DLLs which worked only on 32bit environment. This case can be recreated by changing B's target platform to x86 and running the program on a 64bit machine. What will happen in this case is -
  • A is "AnyCPU" and machine is 64bit so A would be running in 64bit environment
  • A will call a method in a class inside B.
  • B is "x86" so it will not run in 64bit. 
  • So now, a 64bit DLL is calling a 32bit DLL. This is not allowed and an error will be thrown.
What is the resolution? We have 3 -
  • If you have the code for B, you can change the platform target for B from x86 to "AnyCPU"
  • If you don't have code for B, then you can try to search for a 64bit version of B's assembly
  • If this also doesn't work, you can simply change the calling assembly i.e. A's platform target to "x86" and the app will work.