Answer the question
In order to leave comments, you need to log in
How to convert deserialization when passing to null reference types?
Hello.
I am gradually trying to use the null reference type approach in my projects, but so far it is very unusual.
Here is another doubt that caught me by surprise.
My logical chain of reasoning is set out below, I feel that something is wrong in it, but I can’t understand what exactly.
Let's assume the default values I can't use. So:
1. when we declare a class, we must mark it with a ? those fields and properties that can take null, types without ? cannot accept null.
2. since we have fields without ?, they must be initialized when the class is created: either by default or through a constructor. no other way?
3. well, when creating an instance, we only have topass the initial values through the constructor. accordingly, all the code that we used to assign values to fields in the style
oldClass c = new oldClass();
c.field1 = "val1";
c.field2 = "val2";
oldClass x = new oldClass { field1 = "val1", field2 = "val2" };
public class notnullableclass
{
public notnullableclass(string notnull1, string notnull2)
{
this.notnull1 = notnull2;//специально так, чтобы запутать десериализатор
this.notnull2 = notnull1;
}
public string notnull1 { get; set; }
public string notnull2 { get; set; }
}
notnullableclass e1 = new notnullableclass("init1","init2");
string data1 = JsonConvert.SerializeObject(e1);
Console.WriteLine($"e1: notnull1:{e1.notnull1}; notnull2:{e1.notnull2}");
Console.WriteLine($"data1: {data1}");
notnullableclass e2 = JsonConvert.DeserializeObject<notnullableclass>(data1);
Console.WriteLine($"deserialized e2: notnull1:{e2.notnull1}; notnull2:{e2.notnull2}");
string data2 = "{\"notnull1\":\"init1\",\"notnull2\":\"init2\"}";
Console.WriteLine($"data2: {data2}");
notnullableclass e3 = JsonConvert.DeserializeObject<notnullableclass>(data2);
Console.WriteLine($"deserialized e3: notnull1:{e3.notnull1}; notnull2:{e3.notnull2}");
Answer the question
In order to leave comments, you need to log in
NRTs are just annotations and do not commit anything. Although different libraries may use the information from these annotations.
As you can see, after deserialization, the field values are messed up.
And I am using Newtonsoft.Json (13.0.1)
types without ? cannot accept null.
But seriously, how can you still guarantee the correct operation of the code when using the null reference type approach?
Is it still possible to guarantee that the field will not be null and not use the constructor?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question