I already tried a lot of stuff to get rid of all this boring code to check parameters:
Code-Contracts: Gets on your nerves when third-party libraries do not support it.
public void Buy(Product product)
{
Contract.Requires(product != null);
}
PostSharp: Custom attributes.
public void Buy([NotNull] Product product)
{
}
Guard-Class: Static class with helper methods.
public void Buy(Product product)
{
Guard.NotNull(product, "product"); // Repeat parameter name, bad for refactoring.
Guard.NotNull(() => product); // Slow
}
Manual:
public void Buy(Product product)
{
if (product == null)
{
throw new ArgumentNullException("product");
}
}
No with the last version of roslyn there is the option to write extensions to simplify validation. For 90% I check for null references or empty strings, so it might be valuable to have something like this:
public void Buy(required Product product)
{
}
public void Buy(Product product)
{
requires product
}
public void FindUser(required nonempty string name)
{
requires nonempty name
}
So my questions:
You'd like to introduce new keyword, that's not an extension. It's a language feature.
I'm not 100% sure, but you'd have to modify the grammar, introduce new token and syntax tree node. Then, you'd have to specify what kind of IL should be emitted for that construct. That's not a trivial thing. And what you would get after that is your own version of C#, with your own version of C# compiler.
And it would only work for people using this version of compiler.
I don't think it's a good idea.
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