# Wednesday, April 11, 2007
« Memory Mapped Files | Main | Running Application Test Suites »
Detecting .NET 2.0 x64

In the category .NET trivia. I found a weird difference between .NET 2.0 x86 and x64. This code detects that it runs on x64 (at least the .NET 2.0 build included with Vista x64):

WeakReference r = new WeakReference(null);
try { throw new Exception(); }
catch (Exception x) { r.Target = x; }
GC.Collect();
if (r.Target != null)
  Console.WriteLine("Running on x64");

It appears that the last thrown exception is stored in a global (or rather probably thread local) variable and hence not garbage collectable until the next exception is thrown...

Update: I thought this was obvious, but since two commenters have felt the need to point out that you shouldn't use this in production, I'll say it explicitly:I was just pointing out some obscure implementation difference (arguably a bug), do not use this code in production.

Wednesday, April 11, 2007 3:31:01 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [3]
Wednesday, April 11, 2007 5:08:56 PM (W. Europe Daylight Time, UTC+02:00)
I think that it should be a bug in x64 implementation. What happends with this code in Mono x86 and x64?
Thursday, April 12, 2007 7:59:15 AM (W. Europe Daylight Time, UTC+02:00)
Incase anyone ever googles this page looking for X64 detection, the 'sane' way to detect if you are running on X64 ofcourse would be

if (IntPtr.Size == 8)
Console.WriteLine("Running on x64");
else
Console.WriteLine("Running on x86");
Ray
Thursday, April 12, 2007 8:06:47 PM (W. Europe Daylight Time, UTC+02:00)
I think that checking size of pointer is better method.

- It is not depened on hack
- It's faster (exceptions are usually expensive).
Comments are closed.