As you already know, ReSharper provides a lot of helpful hints and suggestions for your .NET code.
Additionally, it has features, that allow it to help you leverage your own code. You just need to add a couple of annotations. Consider the example below.
As you can see, Resharper has detected that one of the arguments should actually be a string with the name matching “stream” and suggested to fix that.
This “feature” is implemented by decorating Enforce.ArgumentNotNull method with the InvokerParameterNameAttribute:
[DebuggerNonUserCode]
public static TValue ArgumentNotNull<TValue>(TValue value,
[InvokerParameterName]
string argumentName) where TValue : class
{
if (value == null)
{
throw new ArgumentNullException(argumentName);
}
return value;
}
In order to get InvokerParameterName (and the other attributes) into your code, you can either reference JetBrains.Annotations or copy and paste them into your code:
Alternatively you can reference Lokad.Shared library that has these annotations, as well as many useful helper methods decorated with them for your convenience.
Here’s the list of annotations currently supported by JetBrains ReSharper:
- StringFormatMethod – method or ctor has format string argument
- InvokerParameterName – the argument should be string literal that matches one of the parameters of the caller function
- AssertionMethod – marked method could halt execution flow, if the condition is satisfied
- TerminatesProgram – marked method terminates the program
- CanBeNull – value of the marked element could be null sometimes, so check for null is needed (bad practice)
- NotNull – value of the marked element could never be null
- CannotApplyEqualityOperator– instance of the marked class (or its inheritors) can not be compared via the == or != (null checks are allowed)
- BaseTypeRequired – decorated attribute can be applied only to the classes that have the specified base.
PS: I expect R# 4.5 to have way more features that improve coding experience. Till that happens, there still are R# Live Templates to explore.
Here’s R# snippet for getting argument null check with a couple of keystrokes:
Enforce.ArgumentNotNull($Argument$, "$Argument$")
Where $Argument$ is suggest parameter name of type System.Object.
I’ve bound this template to “eann” and typing in null checks is like a breeze right now.
Recent research on How to Find Parameter or Variable Name in .NET? has led me to an improved syntax for the sanity check helpers in Lokad Shared:
Enforce.Argument(() => myArgument);