简体   繁体   中英

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?

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.

I would love a better version of Code Contracts, which would need to build faster and offer a cleaner/more expressive syntax.

It doesn't appear your proposal is such a bad idea, as this feature has been proposed: https://github.com/dotnet/roslyn/issues/119

I prefer the syntax in the declaration, and yes, I would use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM