I have a serialization mechanism in place that works on the private fields to determine what should be serialized and what not. The main idea behind the approach is to only serialize the "essence" of the data.
Example:
public class Person {
private readonly string _firstName;
private readonly string _lastName;
public C1(string firstName, string lastName) {
_firstName = firstName;
_lastName = lastName;
}
public string FirstName { get { return _firstName; } }
public string LastName { get { return _lastName; } }
public string FullName { get { return _firstName + " " + _lastName; } }
}
A serialized example object would then look like this (JSON):
{ "firstName": "John", "lastName": "Doe" }
As you can see, serializing based on fields ensures that FullName
is not serialized.
This mechanism was in place for a while now and worked flawlessly. However, with the new read-only auto properties in C# 6.0, the fields have an awkward name like e.g. <FirstName>k__BackingField
.
Of course, I can update my serialization code to extract the actual property name from the backing field and use that name during serialization. What I want to know: Is this a robust solution? Or is the naming of the generated backing fields subject to change?
Note: The reason for this approach is that model classes can remain serialization-agnostic like that. I know that I could also use the [JsonIgnore] attributes to achieve the same, but I don't want to add such attributes to my model classes.
It sounds like you are basing your correlation of backing field to property by a naming convention. Menaing if you have a private field _name
and a property Name
then the field must be the backing field for that property.
Is this a robust solution?
No - a robust solution would be to implement serialization for each type since only it knows for certain which fields tie to which property.
Or is the naming of the generated backing fields subject to change?
This is an implementation detail - MS could decide to change the naming convention however they see fit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With