From Scala language I am used to peppering my code with require statement.
I would use this for things that should NEVER be violated, it is a sanity check and also a kind of "live comment" in the code.
This is the behaviour I would like
// C#
if (!(x > 0)) {
throw new Exception($"x must be positive but was ${x}")
}
but this is hard to read and will be a mess if there many of them at the top of the function.
In Scala I was used to doing this:
// Scala
require(x > 0, s"x must be positive but was ${x}")
// or just
require(x > 0)
It's not much effort to type require(x>0) and very readable.
I find these save me a lot of time when developing in Scala, it's very easy to type them out and often the sanity check catches a mistake fast.
What is the accepted way to do this in C# ?
I saw there are "Code Contracts" and I tried using these but they don't seem to work at all in .NET Core.
It is relatively standard to see a long list of if ... throw at the beginning of methods, but there are the Debug.Assert (for assertions removed from release builds) and Trace.Assert (to keep the assertions in your release builds) methods that appear to be very similar to the Scala require method you mentioned.
See this article about assertions on MSDN for details about how they work and the different overloads.
In your case you could write
Trace.Assert(x > 0, $"x must be positive but was ${x}");
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