Why am I getting a "Possible Null Reference" Warning on an Enum->String conversion?

54 Views Asked by At

I have a private field of type ArmorType. It's an enum. I then make a public property that returns that enum value as a string. But then Visual Studio 2022 tells me that there is a Possible Null Reference Return and I am completely confused as to how that could ever be possible, given that an enum value cannot be null so the returned string could also never be null.

enter image description here

Any explanation as to why? Is Visual Studio just being dumb? Am I missing something fundamental about how C# functions?

2

There are 2 best solutions below

0
CodeMan On BEST ANSWER

If multiple enumeration members have the same underlying value, the GetName method guarantees that it will return the name of one of those enumeration members. However, it does not guarantee that it will always return the name of the same enumeration member. As a result, when multiple enumeration members have the same value, your application code should never depend on the method returning a particular member's name.

private ArmorType armorType;
public string ArmorType => Enum.GetName(typeof(ArmorType), armorType)!;

in net core 8.

0
T.S. On

You're using project setting "enable nullable reference types". you have declared a not-nullable property ArmorType, (string vs string?).

Now, you're trying to use Enum.GetName() declared as

public static string? GetName (Type enumType, object value);

As you see, it returns nullable string. And you're trying to return it via non-nullable property string. Hence, you get this compiler error.

You can declare your property as nullable string or if you guaranteed correct value in this.armorType you can use null-forgiving operator ! as in this.armorType!