I'm working to become proficient with the newest C# language features and .net 8.
I understand that with C# 8.0 and above, the compiler will generate a warning when assigning to a reference type when the value being assigned might possibly be null unless the variable being assigned to is declared as a nullable reference type.
So, for example, I have a function that looks like this:
void ManipulateJson(string jsonString)
{
JsonNode node = JsonNode.Parse(jsonString); // compiler warning
string determinant = node["determinant"].GetValue<string>(); // compiler warning
string id = newId(determinant);
node["id"] = id;
}
The first two lines generate compiler warnings because JsonNode.Parse(node) and node["determinant"] may possibly be null.
If I understand correctly, I could write something like this:
void ManipulateJson(string jsonString)
{
JsonNode? nodeNullable = JsonNode.Parse(jsonString);
JsonNode node = nodeNullable ?? throw new Exception("null JSON value");
JsonNode? determinantNodeNullable = node["determinant"];
JsonNode determinantNode = determinantNodeNullable ?? throw new Exception("determinant is missing from JSON");
string determinant = determinantNode.GetValue<string>(); // compiler warning
string id = newId(determinant);
node["id"] = id;
}
I could have avoided some of the noise above by using the null-forgiving operator, but that seems like it's defeating the point of nullable reference types.
What are the relevant best practices that would help me write code like this in good form for readability and maintainability, especially when I am manipulating more than one or two JSON properties?
JsonNode node = JsonNode.Parse(node);seems quite wrong. Very likely you intented toJsonNode node = JsonNode.Parse(jsonString);or something similar