NotNull Annotation on implicit cast operators


Hi there

Is it possible to write an implicit cast operator in C# using the [NotNull] Attribute?

My attempt so far was:

public struct NotNullable<T> where T : class
    public NotNullable([NotNull]T value)
        if (value == null)
            throw new ArgumentNullException(nameof(value), @"A NotNullable type cannot be null");
        Value = value;

    [ContractAnnotation("notnull => notnull")] // Tried contract annotations to check if they are more strict, but also didn't work
    public static implicit operator NotNullable<T>([NotNull]T value)
        return new NotNullable<T>(value);

It works for the constructor parameter but the implicit cast does not show a warning:

object test = null;
NotNullable<object> notNullableTest = new NotNullable<object>(test); // Parameter test is underlined
notNullableTest = test; // but no warnings are shown here

Thought someone got an idea here or if someone can tell me that it is not possible to do, would help too.


1 comment
Comment actions Permalink

Hello Philipp!


Sorry for delay in responding.

There's no such option in ReSharper, I've filed corresponding feature request in our issue tracker -

Please feel free to comment or vote for it.

Thank you.


Please sign in to leave a comment.