Skip to content

Instantly share code, notes, and snippets.

@vaclavbohac
Created May 9, 2011 15:28
Show Gist options
  • Save vaclavbohac/962739 to your computer and use it in GitHub Desktop.
Save vaclavbohac/962739 to your computer and use it in GitHub Desktop.
Example of binary serialization in C#.
all: test.dll
test.dll: TestSerialization.cs
mono-csc -t:library -pkg:mono-nunit $< -out:$@
test: test.dll
nunit-console $<
clean:
-rm test.dll *.xml
-rm -rf %temp%
-rm *.bin
/**
* Serialization example in C#
*
* @copyright Copyright (c) 2011 Vaclav Bohac
* @license GNU General Public License v3
* @package SerializationTest
*/
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using NUnit.Framework;
namespace SerializationTest
{
[Serializable]
class Person
{
private string name;
private int age;
public string Name
{
set { name = value; }
get { return name; }
}
public int Age
{
set { age = value; }
get { return age; }
}
}
[TestFixture()]
public class SerializationTestSuite
{
[Test()]
public void TestSerialization()
{
// Define object person.
Person p = new Person();
p.Name = "John";
p.Age = 42;
// Serialize object.
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("Person.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, p);
stream.Close();
// Deserialize object.
Stream readStream = new FileStream("Person.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
Person p2 = (Person) formatter.Deserialize(readStream);
readStream.Close();
// Test equality with new object.
Assert.AreEqual(p.Name, p2.Name);
Assert.AreEqual(p.Age, p2.Age);
}
}
}
@samandarbaxodirovich
Copy link

This is so helpfull
,Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment