Introduction
Binary serialization is very common in some scenarios, so, this tip adds this functionality as extension methods in order to provide an easy and comfortable way to use it.
Background
You must know C#, serialization concept and extension methods.
Using the Code
The extension methods are as given below:
public static class Extensions
{
public static void Serialize<T>(this T obj, string filePath=null)
{
filePath = filePath ?? (filePath ?? (obj.GetType().GenericTypeArguments[0].FullName + ".bin"));
using (Stream stream = File.Open(filePath, FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, obj);
}
}
public static T DeSerialize<T>(this T obj, string filePath=null)
{
T result;
filePath = filePath ?? (filePath ?? (obj.GetType().GenericTypeArguments[0].FullName + ".bin"));
if (!File.Exists(filePath)){
return (obj);
}
using (Stream stream = File.Open(filePath, FileMode.Open)){
BinaryFormatter bin = new BinaryFormatter();
result = (T)bin.Deserialize(stream);
}
return (result);
}
}
Sample of use is as follows:
[Serializable()]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
private void testSerialization()
{
List<Person> lstPerson = new List<Person>().DeSerialize();
if (lstPerson.Count() == 0){
lstPerson.Add(new Person() { Name = "Pepe", Age = 60 });
lstPerson.Add(new Person() { Name = "Juan", Age = 70 });
lstPerson.Serialize();
}
foreach (var person in lstPerson){
Console.WriteLine("{0} {1}", person.Name, person.Age);
}
}