Home > Software design >  Serialize generic dictionary
Serialize generic dictionary

Time:06-02

I want to serialize an object. But I want that the object has to be a dictionary (of tkey and tvalue any type).

My code so far:

public static byte[] Serialize<T>(this T source)
{
    try
    {
        if (source == null)
        {
            return null;
        }

        using (var memoryStream = new MemoryStream())
        {
            var binaryFormatter = new BinaryFormatter();

            binaryFormatter.Serialize(memoryStream, source);

            return memoryStream.ToArray();
        }
    }
    catch(Exception e)
    {
        return default(byte[]);
    }
}

Now I want that "source" can only be a Dictionary like Dictionary<int, string>, Dictionary<foo, int>, ...

CodePudding user response:

public static byte[] Serialize<T,V>(this Dictionary<T,V> source) 
{
    try
    {
        if (source == null)
        {
            return null;
        }

        using (var memoryStream = new MemoryStream())
        {
            var binaryFormatter = new BinaryFormatter();

            binaryFormatter.Serialize(memoryStream, source);

            return memoryStream.ToArray();
        }
    }
    catch(Exception e)
    {
        return default(byte[]);
    }
}

with this definition only Dictionary<Key,Value> can be passed to the method.

In example https://dotnetfiddle.net/SQY6zs you can see that Serialize() can be applied to Dictionary<int,bool> but not to int

  • Related