Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Code Contracts to have a compile time assert in C#?

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?

like image 883
sharptooth Avatar asked Jul 19 '13 08:07

sharptooth


People also ask

What is the advantage of compile time assertions?

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.

What are codecontracts and how to use them?

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.

What is the use of assert in C++?

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.

What are preconditions in a code contract?

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.


Video Answer


1 Answers

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

like image 68
Etienne Maheu Avatar answered Oct 21 '22 17:10

Etienne Maheu