I need to serialize/deserialize
classes using protobuf-net. For some properties of my classes, I need to define a default value. I did this by setting the values of the properties. In some cases this default value overwrites the value from the protobuf data.
Code Sample:
public class Program
{
static void Main(string[] args)
{
var target = new MyClass
{
MyBoolean = false
};
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, target);
stream.Position = 0;
var actual = Serializer.Deserialize<MyClass>(stream);
//actual.MyBoolean will be true
}
}
}
[ProtoContract(Name = "MyClass")]
public class MyClass
{
#region Properties
[ProtoMember(3, IsRequired = false, Name = "myBoolean", DataFormat = DataFormat.Default)]
public Boolean MyBoolean { get; set; } = true;
#endregion
}
MyBoolean will have a value of true after deserializing the data.
How can I fix this behavior?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
For performance reasons default values are not serialized at all. The default of bool is false. Your default is true. To make this work you have to make your default value known with the DefaultValueAttribute
:
[ProtoMember( 3, IsRequired = false, Name = "myBoolean", DataFormat = DataFormat.Default )]
[DefaultValue(true)]
public Boolean MyBoolean { get; set; } = true;
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