Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Resharper from removing [CanBeNull] when typing "?" at the end of a reference type name?

I am going through the process of converting my .Net 4.8 (not Core!) projects to use the new C# 8 "nullable reference" feature.

To do so, I am changing each source code file in turn by adding #nullable enable and decorating all nullable references with a ? suffix. This allows me to convert all my code in a piecemeal fashion to use the new feature.

Now consider the following method in a source file with #nullable enable specified:

#nullable enable

[CanBeNull] public static string Test([CanBeNull] string arg)
{
    return arg;
}

If I type a '?' after either of the string declarations (in order to use the new C# 8 "nullable" feature), Resharper removes the [CanBeNull] attribute:

public static string? Test(string? arg)
{
    return arg;
}

However, if that attribute is removed then Resharper does not warn me about possible null-reference uses in other source files. (This would not be an issue if all the source files had #nullable enable specified, but because I am converting the files in a piecemeal fashion, there are many files that do not yet have #nullable enable specified, so the compiler will not warn me about possible null-reference uses - and neither will Resharper, because the [CanBeNull] was removed.)

So my question is this:

Is there a way of stopping Resharper from removing the [CanBeNull] attribute when I type a ? at the end of a reference type name?

I've searched through all the Resharper options but I haven't managed to find one for this.

like image 776
Matthew Watson Avatar asked Oct 18 '25 17:10

Matthew Watson


1 Answers

I asked the question on the Resharper support forums, and have received a solution:

https://resharper-support.jetbrains.com/hc/en-us/community/posts/360006676140-How-to-stop-Resharper-from-removing-CanBeNull-when-typing-at-the-end-of-a-reference-type-name-

To fix it:

  1. Go to Extensions -> Resharper -> Options -> Environment -> Editor Behavior -> C#
  2. Locate and turn off the option "Annotate nullability on '!'/'?' after type name".
  3. Locate and turn off the option "Annotate nullability on '!'/'?' at other positions"
like image 164
Matthew Watson Avatar answered Oct 21 '25 07:10

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!