I have a class property set, and fixed in the constructor, example below is a Guid.NewGuid()
..
The rationale being to only allow the class to populate, on creation.. so it's set in the constructor, and marked only as get;
- works fine, until i serialize / deserialize to Json.
It seems that because there is no set;
the deserialization fails.. and the constructor steps in and creates a new guid
I have tried internal, private, and protected set .. but all result in a regeneration of the property, the only way i can get it to work is by marking Id as {get;set;}
,
class Foo
{
public Foo() => Id = Guid.NewGuid().ToString();
public string Id { get; set; }
}
which then means you can simply do:
var obj = new Foo();
obj.Id = "Any Old Rubbish";
Is there a way around this at all?
Short sample:
class Program
{
static void Main()
{
var obj = new Foo();
Console.WriteLine(obj.Id);
var serialize = JsonConvert.SerializeObject(obj);
var deserialize = JsonConvert.DeserializeObject<Foo>(serialize);
Console.WriteLine(deserialize.Id);
Console.ReadLine();
}
}
class Foo
{
public Foo() => Id = Guid.NewGuid().ToString();
public string Id { get; }
}
Output:
7868a298-f20d-4719-85ef-ba64c8658819
34fe422c-9555-4d17-ae1a-9fbf21af1b71