Auto implemented properties and serialization - c#

I'm going through a lot of code and marking classes which I now want to persist with the Serialization attribute. I haven't written the binary serialization/deserization engine as yet so guess I will answer my own question once that's complete! - but thought I'd try get an earlier response here if that's OK. I've come across some code which contains a property such as:
public string Id
{
get;
set;
}
Does the "Id" get serialized? I understand that underneath the compiler auto creates a class member, but does this get serialized correctly (since all the data members of the class instance are written to storage)? It feels like it won't since you can't place the Serialized/NonSerialized attribute on properties.
Thanks in advance.

You can use the [field:NonSerialized] attribute to mark the backing field of events as being non-serializable, however it seems this is not possible with auto-properties. With auto-properties the backing fields will be serialized and the only way to prevent that behaviour is to transform them into regular properties and annotate the explicit backing fields with [NonSerialized] as normal.

As #John has pointed out in his comments, the BinaryFormatter (System.Runtime.Serialization.Formatters.Binary) will serialize your auto-generated backing field. You can use custom serialization by implementing the ISerializable interface and then decide for your class which values are serialized or not.

Related

protobuf-net: properties versus fields

In our project, we have a data transfer object (DTO) class which is decorated with a [ProtoContract] attribute, and all of its members are public properties decorated with [ProtoMember] attributes - except that one of the members is a public field (by accident). Now we want to change the one public field into a property. Can this have an impact about the implicit protobuf contract? (We want to avoid breaking changes, and I suppose that this change is non-breaking, but I want to be sure.)
Yes, that's absolutely fine; protobuf-net won't care, and the serialized payload will remain identical.

C# - Does it make sense to have an empty interface with a class level attribute to specify common behavior?

I have several classes that serve as data transfer objects (in C#). These classes are all serialized using JSON.Net to be sent to an API. Unfortunately, the property names specified in the API don't have standardized naming conventions. Some properties use camel casing, some use snake casing, some all lowercase, and so on. So, I need to account for this when serializing the DTOs to JSON. Also, when properties are null, I want them to be excluded from the serialized JSON.
So, here was my solution. I created an empty interface called ISerializableDto and added class level attributes specifying that properties should be excluded when null and the default property naming strategy is snake casing.
[JsonObject(
NamingStrategyType = typeof(Newtonsoft.Json.Serialization.SnakeCaseNamingStrategy),
ItemNullValueHandling = NullValueHandling.Ignore)]
public interface ISerializableDto
{
}
All of my DTO classes inherit from this interface. When the naming convention for a property in one of the DTO classes is not snake cased, I just specify the property name explicitly through a property level attribute.
public class ExampleDto : ISerializableDto
{
public string SomeRandomPropertyName { get; set; } // This will serialize to "some_random_property_name"
[JsonProperty(PropertyName = "someRandomCamelCasedPropertyName")]
public string SomeRandomCamelCasedPropertyName { get; set; } // This will serialize to "someRandomCamelCasedPropertyName"
}
This all works fine. I can do a simple JsonConvert.SerializeObject(myDtoObject) and it behaves exactly as I intended. The property names are snake cased unless otherwise specified and null properties are excluded. But, I'm not confident this is the best way to go about doing this.
Does it make sense to have an empty interface with a class level attribute to specify common behavior?
I could remove the interface entirely and put the class level attributes on each DTO class. But, someone might miss it if they need to add a new DTO class later on. Or, I could even specify these behaviors in the JsonConvert.SerializeObject call. But my worry there is that some of the naming behavior is specified in the DTO class, and some is specified externally.
Is there some better way of doing this?
I would probably do this by creating an attribute [SerializableDto] that derives from JsonProperty and contains the settings that you want. Since all the rest of your specifiers (like for the property names) are done with attributes it seems more consistent. If you put it in an interface you create a more complex situation where some of the specification is done by implementing an interface while other related specification is done using attributes.
Have not checked whether or not JsonProperty is sealed. If it is then your situation is trickier. You might still be able to do it though using an attribute that dynamically attaches the Json attribute using TypeDescriptor.AddAttributes.

Reacting on serialize and deserialize of an instance

I have a class which i am serializing. I annotated it with [Serializable] and i am using binary serializer. Everything works fine.
But later i introduced new properties, which cannot be serialized (lets say they contain a lot of mess about GUI which does not need to be rembered). I can compute these properties based on other properties of class.
I need to do it two times, when I serialize - clean mess and enter stabile state ready for serialization. And deserialization - again compute all needed properties.
I need to react on 'events' instance is being serialized/deserialized.
However I can't find these events because I am not implementing the interface ISerializable or abstract class Aserializable but only class atribute [Serializable].
I do not know when class is being serialized because it is not the concern of this class; it is serialized as a field of another class.
Is there a way I can react on those events?
You can use OnDeserializedAttribute and its related attributes (OnSerializing, OnSerialized, OnDeserializing) to create special methods that are called during the serialization/deserialization process.
Build Custome Serialization by Implementing ISerializable. Use OnSerializingAttribute, to manipulate object before serilazation and OnDeserializingAttribute, to manipulate before deserialization.
Have you considered per chance the [XmlIgnoreAttribute] attribute? It will prevent a property to be serialized. No need to tamper withe the serialization workflow.
My bad, didn't realize you wanted to reload some property on deserialization. So why not serialize these? In an optional subObject, or whatever?

Adding a method to an object that is serialized, but it doesnt' need to be serialized

I have an object that is currently serialized, and I want to do add a method to this class. The method shouldn't be serialized as it doesn't hold any state or anything, but it will modify the classes data but this doesn't need to be serialized (it will parse the value of a serializable string property).
How can I add this method? Or should I have this method on another utility class instead?
Methods aren't serialized. Only properties and fields are serialized. And Properties are only eligible for serialization if using DataContractSerializer (BinaryFormatter will only serialize Properties' underlying fields).
Adding this method won't be a problem, methods aren't serialized.
If you have access to the class then as I understand it serialization deals with properties and fields. Methods don't need to be and don't get serialized. They process the data
Quick answer: Most cases shouldn't affect unserialize an object.
Only fields are serialized. Methods and properties arent (properties are methods). The XmlSerializer is an exception; it only looks at public properties, and those must be public get / set if you are to deserialize them.

Why do you have to mark a class with the attribute [serializable]?

Seeing as you can convert any document to a byte array and save it to disk, and then rebuild the file to its original form (as long as you have meta data for its filename etc.).
Why do you have to mark a class with [Serializable] etc? Is that just the same idea, "meta data" type information so when you cast the object to its class things are mapped properly?
Binary serialization is pretty powerful, it can create an instance of a class without running the constructor and can set fields in your class that you declared private. Regular code can of course not do this. By applying the [Serializable] attribute, you explicitly give it the go-ahead to mess with your private parts. And you implicitly give that permission to only the BinaryFormatter class.
XML serialization doesn't need this kind of okay, it only serializes members that are public.
DataContractSerializer can serialize private members as well. It therefore needs an explicit okay again, now with the [DataContract] attribute.
First off, you don't have to.
It is simply a marker interface that tells the serializer that the class is composed of items that it can serialize (which may or may not be true) and that is can use the default serialization.
The XMLSerializer has the additional requirement to have a zero parameter constructor to the class.
There are other serializers that use contracts for serialization (such as the DataContractSerializer) - they give you more control over serialization than simply marking a class as Serializable. You can also get more control by implementing the ISerializable interface.
It's basically metadata that indicates that a class can be serialized, nothing more.
It is required by a lot of framework serializers, which refuse to deal with types not having this attribute applied to them.
Serialization can create security holes and may be plagued by versioning problems. On top of that, for some classes, the very idea of serialization is outright nonsense.
For details, see the excellent answers to Why Java needs Serializable interface?, especially this one, this one, and this one. They make the case that serialization should be a feature you have to explicitly opt into.
For a counterpoint, the accepted answer to that question makes the case that classes should be serializable by default.
It indicates to the serializer that you want that class to be serialized as you may not want all properties or classes to be serialized.
I see it as a reminder that I will allow the class to be serialized. So you don't implicitly serialize something you shouldn't.
Don't know it that is designers' intention.
BTW, I just love BinaryFormatter and use it as much as I can. It handles pretty much of the stuff automatically (like rebuilding complex object graphs with recurring references spread throughout the graph).

Categories