Tuesday, August 23, 2011

GetHashCode for serializable object extention

The following code demonstrates how to implement HashCode computation based on uniqueness content of abstract object. You can pass an object graph which will estimate HashCode based on member values:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace PMunin.com
{
public static class GetHashCodeExtension
{
/// <summary>
/// Retrieves HashCode of serializable object, based on serializing object to bytes, converting bytes to string and returning its hashcode
/// </summary>
/// <param name="serializableObject"></param>
/// <returns></returns>
public static int GetHashCodeOfSerializableContent(this object serializableObject)
{
var formatter = new BinaryFormatter();
using (var ms = new MemoryStream())
{
formatter.Serialize(ms, serializableObject);
var resStr = Convert.ToBase64String(ms.ToArray());
return resStr.GetHashCode();
}
}

}
}


No comments:

Post a Comment