0

I have the following piece of code:

string returnValue;
var registryValue = key.GetValue("something") ?? throw new InvalidOperationException();
returnValue = registryValue.ToString();

In the second line VS tells me CS8600 - Converting null literal or possible null value to non-nullable type. I don't understand why it gives this warning. At this point registryValue is definetely not null, thus as far as I know .ToString() cannot return null.

Are there any non null objects, so that object.ToString() returns null or is this just a case of IntelliSense being unaware, that null cannot occure here? So can I safely use returnValue = registryValue.ToString()!; or do I have to handle possible null here?

AracKnight
  • 357
  • 5
  • 18
  • Have a look at how `ToString` is declared: https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=net-7.0 – Sweeper Jun 06 '23 at 08:01
  • 1
    Anyone can define their own type and override the `ToString` method so the answer is obviously yes, that method can return `null`. It would be odd to do so but that doesn't mean that there couldn't be a reason. – jmcilhinney Jun 06 '23 at 08:04

0 Answers0