Is there a way to tell the compiler that a following check will ensure that Item is not null and it is safe in the rest of the code and the CS8601 warning is not needed?
The warning, which technically true, does not consider that it's handled in the subsequent line and doesn't need to generate a warning.
Console.WriteLine("Hello, World!");
var test = new Test();
test.Init();
public class Test
{
public record Item(string Name, int Total);
public Item MyItem { get; set; } = null!;
public int MyItemTotal { get; set; }
public void Init()
{
MyItem = GetItems().FirstOrDefault();
if (MyItem == null)
{
return;
}
else
{
MyItemTotal = MyItem.Total;
}
}
private List<Item> GetItems()
{
return new List<Item>();
}
}
In the above code MyItem = GetItems().FirstOrDefault(); shows as a warning, which is technically correct. However, the following line does a check and exits. I am looking for a way to tell the compiler "I know and I'm handling it, no need to warn."
The main reason is that I don't want to ignore warnings and I don't want pragmas all over the code.
Is there a clean way to do it?
EDIT Here's an example on a Razor webpage where if MyItem is null we would redirect away from the page. It is safe to assume in this code that MyItem will never be null. But the warning will always be displayed because Item is not nullable.
public Item MyItem { get; set; } = null!;
public IActionresult OnGet()
{
MyItem = GetItems().FirstOrDefault();
if (MyItem == null)
{
return Redirect("/");
}
return Page();
}
Itemas both the name of a type and the name of a variable. (I'd also strongly encourage you to follow normal. NET naming conventions, e.g. starting local variables with lower case letters, even for sample code. Anything that distracts the reader harms the post.)MyItemcan be changed by a different thread between assigning the value and checking the value. If want to signal the compiler the guarantee that it won't be null, don't allow anybody to change it behind your back – use a local variable, those can't be changed!as needed.