Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter.Checking with Roslyn

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:

  1. Are there any roslyn extensions or other postcompiler?
  2. Do you know how any good resource to write a custom extension like this.
  3. Would you use such an extension and if so, what is the preferred syntax. If not, why?
like image 597
SebastianStehle Avatar asked Jan 22 '26 15:01

SebastianStehle


1 Answers

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.

like image 133
MarcinJuraszek Avatar answered Jan 24 '26 04:01

MarcinJuraszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!