CS8601 Notice Inside A List<T>.ForEach(Action<T>) ForEach Call

Answered

Consider the code below:

[StepArgumentTransformation]
public static IEnumerable<MyClass> MyClassTransform(Table myClassTable)
{
var myItems = myClassTable.CreateSet<MyClass>().ToList();
myItems.ForEach(item =>
{
item.Field1 = item.Field1?.PadRight(15);
item.Field2 = item.Field2?.PadRight(15);
});

return myItems;

With R#, the two assignment lines item.Field1?.PadRight(15) and item.Field2?.PadRight(15) trigger a CS8601 possible null reference assignment warning. I'm not sure why this is because item is known to be not-null and thus the left hand side of the assignment is not triggering a warning. Is this a R# bug, am I maybe not understanding the nature of the ForEach call, or is something else going on?

3 comments
Comment actions Permalink

Hello Thomas,

 

thank you for the feedback.

Could you please provide a screenshot demonstrating the problem?

We'd be also grateful if you could provide a stripped solution in which the problem is reproduced. You can do it privately via "Submit a request" form at the top of the page.

Unfortunately, I couldn't reproduce it from scratch.

Thank you.

0
Comment actions Permalink

Hi Angelina,

I put an example project up here: https://github.com/tparikka/ResharperCS8601

Having played with it a little, it seems like it might be specifically occurring only when nullable reference types are enabled - the example project is configured for that as well.

Thanks!

0
Comment actions Permalink

Hello,

 

thank you for the provided info.

Here are comments from our developer:

1 - properties of ReportName and OwnerName are specified as not nullable;

2 - ?. returns null if operand is null. ReSharper knows the variable cannot be null, while the compiler completely trusts to the user and provides a waning as user performs null checking for the variable. So ReSharper tells for sure that item cannot be null and ?. is redundant. Still we should show the compiler warning  otherwise user can get warnings or even errors during compilation (if warningsAsErrors option is used).

So you should decide if item can be null (then ?. remains, CreateSet() is changed to CreateSet<report?>() and fallback value is specified after ?.) or that item cannot be null (?. is removed and no more warnings appear)

In short,  compiler considers that ?. always can be executed and always can return null even if it's applied to not null constant, e.g.. 

 #nullable enable System.Type M() => ""?.GetType(); 

https://sharplab.io/#v2:CYLg1APgAgTABAYQLACgDeq5bgYgHYCuANkQIYBGRApnFXhdZtlAIwB0AKgJ4AONAsgAoAlHAC8APjgAiaQH42AcSoAXbnxEBuVAF8gA</report?>

Please let me know if you have any more questions.

Thank you.

0

Please sign in to leave a comment.