Johan Larsson Johan Larsson - 1 month ago 8
C# Question

Is there a way to specify a post condition using resharper attributes?

Say we have a method

internal static void NotNull<T>(T value)
where T : class
{
if (value == null)
{
throw new ArgumentNullException();
}
}


Is there a way to tell Resharper's static analysis that a value passed to this method is never null after?

Answer

There are two ways to achieve that:

[JetBrains.Annotations.ContractAnnotation("halt <= null")]
public void NotNull(object obj)
{
  // ...
}

and an extension method like

[JetBrains.Annotations.NotNull]
public static T NotNull<T>(this T obj)
{
  // ...
  return obj;
}

Personally I like the second more, because it's fluent and you can just continue with your code :)