Has suppressing CS8632 any bad consequences?
Asked Answered
U

1

6

I'm working on a codebase that is not yet <Nullable>enable</Nullable>. There is a vague notion that we will activate nullablity sometime soonish.

While writing code I'm sometimes tempted to use nullability operators (e.g. void Foo(string? stringOrNull) {}). Mostly to explicitly mark that this argument is intended to accept null and that the implementation does/should respect that. Obviously I won't get any potential wrong-usage compiler-warning befits until nullability is activated. But at least I have noted my intent at the implementation site and whenever nullability is activated it should be picked up.

But of cause, for now, I get the compiler warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Can I just suppress that or are there any unintended consequences?

Undirected answered 3/2, 2021 at 12:5 Comment(2)
Feels a bit dirty to me, though I don't have a good reason. I'm pretty sure the IL is the same with or without the ?. Can't you just add #nullable enable in the files where you use it? It should make the future migration to use it a lot smoother.Kapellmeister
@Kapellmeister hm, that's a good alternative.Undirected
G
1

There are 2 main ways to handle null in C#:

  • Use string with <Nullable>disable</Nullable> and add null-checks everywhere where a string is used. (legacy behavior)
  • Use string? with <Nullable>enable</Nullable> and add null-checks everywhere where a string? is used but not where string is used. (new and recommended, because when nullable is enabled then you will get a CS8625-warning at the place where you assign null to a string-variable (e. g. when calling Foo(null) with Foo(string myParam)). but it is only a warning, so you can pass null anyway but the function-caller gets at least a appropriate hint that passing null is not intended here. and if you want to allow null as argument you would change the parameter-type to string? and then the warning for the caller will disappear. this is a more resilient approach when dealing with null than using the "nullable=disable"-behavior.)

So the warning wants to say that using string? with <Nullable>disable</Nullable> does not really make sense (even if it works) because string? is only intended to be used with <Nullable>enable</Nullable> (or in a nullable-block defined in another way). And this can maybe confuse/mislead some developers when thinking about whether the caller or the implementer is supposed to do a null-check for the parameter.

Apart from that there is no bad consequence to ignore the warning.

Gladiate answered 10/9 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.