Domanda

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?

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top