KGy SOFT

BinarySerializationFormatter Class

KGy SOFT Core Libraries Help
Serializes and deserialized objects in binary format.
See the Remarks section for details and for the differences to BinaryFormatter.
Inheritance Hierarchy

SystemObject
  KGySoft.Serialization.BinaryBinarySerializationFormatter

Namespace:  KGySoft.Serialization.Binary
Assembly:  KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 5.0.0
Syntax

public sealed class BinarySerializationFormatter : IFormatter

The BinarySerializationFormatter type exposes the following members.

Constructors

  NameDescription
Public methodBinarySerializationFormatter
Creates a new instance of BinarySerializationFormatter class.
Top
Properties

  NameDescription
Public propertyBinder
Gets or sets the SerializationBinder that performs type conversions to and from string.
See the Remarks section for details.
Public propertyContext
Gets or sets the StreamingContext used for serialization and deserialization.
Public propertyOptions
Options used for serialization and deserialization.
See the BinarySerializationOptions enumeration for details.
Public propertySurrogateSelector
Gets or sets an ISurrogateSelector can be used to customize serialization and deserialization.
Top
Methods

  NameDescription
Public methodDeserialize
Deserializes the specified part of a byte array into an object.
Public methodDeserializeByReader
Deserializes data beginning at current position of given reader.
Public methodDeserializeFromStream
Deserializes data beginning at current position of given stream.
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodSerialize
Serializes an object into a byte array.
Public methodSerializeByWriter
Serializes the given data by using the provided writer.
Public methodSerializeToStream
Serializes the given data into a stream.
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Top
Extension Methods

  NameDescription
Public Extension MethodConvert(Type, CultureInfo)Overloaded.
Converts an Object specified in the obj parameter to the desired targetType.
See the Examples section of the generic ConvertTTarget(Object, CultureInfo) overload for an example.
(Defined by ObjectExtensions.)
Public Extension MethodCode exampleConvertTTarget(CultureInfo)Overloaded.
Converts an Object specified in the obj parameter to the desired TTarget.
(Defined by ObjectExtensions.)
Public Extension MethodIn (Defined by ObjectExtensions.)
Public Extension MethodTryConvert(Type, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvert(Type, CultureInfo, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvertTTarget(TTarget)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvertTTarget(CultureInfo, TTarget)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions.)
Top
Remarks

Caution note Caution
The fundamental goal of binary serialization is to store the bitwise content of an object, hence in general case it relies on field values (including private ones), which can change from version to version. Therefore, binary serialization is recommended only for in-process purposes, such as deep cloning or undo/redo, etc. If it is known that a type will be deserialized in another environment and it can be completely restored by its public members, then a text-based serialization (see also XmlSerializer) can be a better choice.

BinarySerializationFormatter aims to serialize objects effectively where the serialized data is almost always more compact than the results produced by the BinaryFormatter class.

BinarySerializationFormatter natively supports all of the primitive types and a sort of other simple types, arrays, generic and non-generic collections.

Note Note
Serialization of natively supported types produce an especially compact result because these types are not serialized by traversing and storing the fields of the object graph recursively. This means not just better performance for these types but also prevents compatibility issues between different platforms because these types are not encoded by assembly identity and type name. Serialization of complex types can be somewhat slower for the first time than by BinaryFormatter but the serialized result is almost always shorter than the one by BinaryFormatter, especially when generic types are involved.

Even if a type is not marked to be serializable by the SerializableAttribute, then you can use the RecursiveSerializationAsFallback option to force their serialization. Alternatively, you can implement the IBinarySerializable interface, which can be used to produce a more compact custom serialization than the one provided by implementing the ISerializable interface. A custom serialization logic can be applied also by setting the SurrogateSelector property.

Similarly to BinaryFormatter, ISerializable implementations are also supported, and they are considered only for types marked by the SerializableAttribute, unless the RecursiveSerializationAsFallback option is enabled for the serialization.

As BinarySerializationFormatter implements IFormatter it fully supports SerializationBinder and ISurrogateSelector implementations.

Tip Tip
A SerializationBinder can be used to deserialize types of unmatching assembly identity and to specify custom type-name mappings in both directions. Though BinarySerializationFormatter automatically handles TypeForwardedToAttribute and TypeForwardedFromAttribute (see also the IgnoreTypeForwardedFromAttribute option), you can use also the ForwardedTypesSerializationBinder, especially for types without a defined forwarding. The WeakAssemblySerializationBinder can also be general solution if you need to ignore the assembly version or the complete assembly identity on resolving a type. If the name of the type has also been changed, then the CustomSerializationBinder can be used. See also the Remarks section of the Binder property for more details.
Tip Tip
An ISurrogateSelector can be used to customize serialization and deserialization. It can be used for types that cannot be handled anyway for some reason. For example, if you need to deserialize types, whose field names have been renamed you can use the CustomSerializerSurrogateSelector. Or, if the produced raw data has to be compatible with the obfuscated version of a type, then it can be achieved by the NameInvariantSurrogateSelector.

There are three ways to serialize/deserialize an object. To serialize into a byte array use the Serialize method. Its result can be deserialized by the Deserialize method. Additionally, you can use the SerializeToStream/DeserializeFromStream methods to dump/read the result to and from a Stream, and the the SerializeByWriter/DeserializeByReader methods to use specific BinaryWriter and BinaryReader instances for serialization and deserialization, respectively.

Caution note Caution
In .NET Framework almost every type was serializable by BinaryFormatter. In .NET Core this principle has been radically changed. Many types are just simply not marked by the SerializableAttribute anymore (eg. MemoryStream, CultureInfo, Encoding), and also there are some others, which still implement ISerializable but their GetObjectData throw a PlatformNotSupportedException now. Binary serialization of these types are not recommended anymore. If you still must serialize or deserialize such types see the Remarks section of the CustomSerializerSurrogateSelector for more details.

Natively supported simple types

Following types are natively supported. When these types are serialized, no recursive traversal of the fields occurs:

Note Note

Natively supported generic collections

Following generic collections are natively supported. When their generic arguments are one of the simple types or other supported collections, then no recursive traversal of the fields occurs:

Note Note

Tip Tip
The shortest result can be achieved by using  classes or value types as array base types and generic parameters.

Natively supported non-generic collections

Following non-generic collections are natively supported. When they contain only other natively supported elements, then no recursive traversal of the fields occurs:

Note Note

Serialization events

BinarySerializationFormatter supports calling methods decorated by OnSerializingAttribute, OnSerializedAttribute, OnDeserializingAttribute and OnDeserializedAttribute as well as calling IDeserializationCallback.OnDeserialization method. Attributes should be used on methods that have a single StreamingContext parameter.

Note Note
Please note that if a value type was serialized by the CompactSerializationOfStructures option, then the method of OnDeserializingAttribute can be invoked only after restoring the whole content so fields will be already restored.

Examples

Tip Tip
Try also online.
The following example demonstrates the length difference produced by the BinarySerializationFormatter and BinaryFormatter classes. Feel free to change the generated type.
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using KGySoft.CoreLibraries;
using KGySoft.Serialization.Binary;

public static class Example
{
    public static void Main()
    {
        IFormatter formatter;

        // feel free to change the type in NextObject<>
        var instance = ThreadSafeRandom.Instance.NextObject<Dictionary<int, List<string>>>();
        Console.WriteLine("Generated object:   " + Dump(instance));

        using (var ms = new MemoryStream())
        {
            // serializing by KGy SOFT version:
            formatter = new BinarySerializationFormatter();
            formatter.Serialize(ms, instance);

            // deserialization:
            ms.Position = 0L;
            object deserialized = formatter.Deserialize(ms);

            Console.WriteLine("Deserialized object " + Dump(deserialized));
            Console.WriteLine("Length by BinarySerializationFormatter: " + ms.Length);
        }

        using (var ms = new MemoryStream())
        {
            // serializing by System version:
            formatter = new BinaryFormatter();
            formatter.Serialize(ms, instance);
            Console.WriteLine("Length by BinaryFormatter: " + ms.Length);
        }
    }

    private static string Dump(object o)
    {
        if (o == null)
            return "<null>";

        if (o is IConvertible convertible)
            return convertible.ToString(CultureInfo.InvariantCulture);

        if (o is IEnumerable enumerable)
            return $"[{String.Join(", ", enumerable.Cast<object>().Select(Dump))}]";

        return $"{{{String.Join("; ", o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => $"{p.Name} = {Dump(p.GetValue(o))}"))}}}";
    }
}

// This code example produces a similar output to this one:
// Generated object:   [{Key = 908558467; Value = [abufaji, xica]}, {Key = 2026569158; Value = [hivelu]}]
// Deserialized object [{Key = 908558467; Value = [abufaji, xica]}, {Key = 2026569158; Value = [hivelu]}]
// Length by BinarySerializationFormatter: 43
// Length by BinaryFormatter: 2171
See Also

Reference