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?
Note compile time assertions have advantages over runtime ones. They don't need to be called in a function and so can be defined at a structure declaration site for example. You catch any errors earlier and there is no chance of missing the assertion in testing.
First of all, let's understand what CodeContracts are, according to microsoft docs: Code contracts provide a way to specify preconditions, postconditions, and object invariants in your code. Preconditions are requirements that must be met when entering a method or property.
For example, they can be used to check the state a code expects before it starts running or state after it finishes running. Unlike normal error handling, assertions are generally disabled at run-time. Therefore, it is not a good idea to write statements in assert () that can cause side effects.
Code contracts provide a way to specify preconditions, postconditions, and object invariants in .NET Framework code. Preconditions are requirements that must be met when entering a method or property. Postconditions describe expectations at the time the method or property code exits.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With