MemberNotNullIfNotNull
#8281
Unanswered
ds5678
asked this question in
Language Ideas
Replies: 2 comments 4 replies
-
In what situation might this be useful? |
Beta Was this translation helpful? Give feedback.
4 replies
-
Yeah, I was thinking I could try and use For instance, I have a class which gets initialized post construction through an exterior factory which loads/processes data in bits as a file is read. After that process though (if successful), I'll know the members won't be null. So, it'd be great if I could tell the compiler that somehow so I don't have to worry about the null warnings everywhere I use the properties. public static LevelData LoadLevel(string filePath)
{
LevelData levelData = new();
// Level Loading Logic from file, etc...
...
levelData.Title = valueFromFile;
...
// Maybe I have to call some method for final check or to hook into a bool return for MemberNotNullWhen, but I'm fine with that
if (levelData.Initialize())
{
return levelData;
}
throw InvalidOperationException("Level can't be loaded...");
}
public class LevelData
{
public string? Title { get; set; }
/// <summary>
/// Called by LevelLoader after all data is loaded.
/// </summary>
[MemberNotNullWhen(true, nameof(Title))]
public bool Initialize()
{
// Do other processing/checks, just simplified for sake of example
return Title != null;
}
}
[TestMethod]
public void TestLevelLoading()
{
var level = LevelLoader.LoadLevel("Level.txt");
Assert.AreEqual("I won't be null here...", level.Title); // Shouldn't say that Title might be null here
// In my case I'm loading some array data, so I get a CS8602 on my array property of a possible null dereference
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
It's very common for the null status of a member to be dependent on the null status of other values.
Beta Was this translation helpful? Give feedback.
All reactions