NotNull Annotation on implicit cast operators Follow
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.
Please sign in to leave a comment.
Sorry for delay in responding.
There's no such option in ReSharper, I've filed corresponding feature request in our issue tracker - https://youtrack.jetbrains.com/issue/RSRP-465953
Please feel free to comment or vote for it.