7

According to this answer C# now has "code contracts" that should be usable instead of C++ compile time asserts. Now I have this magic code:

IntPtr pointer;
//blahblahblah
pointer = new IntPtr(pointer.ToInt32() + Marshal.SizeOf(typeof(SomeStruct)));

that requires IntPtr to be of the same size as Int32. So I want a compile time assert for that - something like this C++ code

static_assert(sizeof(IntPtr)==sizeof(Int32))

So I tried the following:

System.Diagnostics.Contracts.Contract.Assert(false); //just to test it
pointer = new IntPtr(pointer.ToInt32() + Marshal.SizeOf(typeof(SomeStruct)));

I pass false into Assert() so that it surely fails, but the compilation passes just fine.

So how do I use code contracts to have a compile time assert?

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • 2
    It's still not properly folded into C# - despite the `Contracts` classes being in `mscorlib`, you still have to separately install and then enable contract checking. There's no sign of the support being baked into VS2013, and the add-ins haven't been updated for it. – Damien_The_Unbeliever Jul 19 '13 at 08:28
  • By the way, the [Code Contracts extension](http://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970?SRC=VSIDE) was updated last week to support VS2013. – Damien_The_Unbeliever Aug 20 '13 at 08:27

1 Answers1

2

That is because code contracts are not the same as compile time asserts. They are still runtime code but they also come with a static analysis rule set that you can enable in your projects to do what you are looking for.

Take a look at this question which looks like it already answers this issue very well: Contract.Assert do not throw compilation error

Community
  • 1
  • 1
Etienne Maheu
  • 3,235
  • 2
  • 18
  • 24