Click here to Skip to main content
15,896,201 members
Articles / Programming Languages / C#

Bend the .NET Object to your Will!

Rate me:
Please Sign up or sign in to vote.
4.83/5 (25 votes)
14 Jan 2009CPOL4 min read 47K   123   70  
Clone, serialize, and deep-compare any .NET object, regardless of type
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace CodeProject.Batte.ObjectMastery
{
	/*
	 * StringExtensions.cs
	 * Author: John Batte
	 * Last Modified: 1/5/2009
	 * See http://www.codeproject.com/info/cpol10.aspx for license details
	 */

	/// <summary>
	/// Provides object serialization extensions for strings.
	/// </summary>
	public static class StringExtensions
	{
		/// <summary>
		/// Converts the string to an object instance
		/// of the specified type.  Assumes that the string
		/// was created using object.ToBinaryString().
		/// </summary>
		/// <typeparam name="T">The type to convert to.</typeparam>
		/// <param name="serializedObject">The string.</param>
		/// <returns>The converted object instance.</returns>
		public static T ToObject<T>(this string serializedObject)
		{
			var formatter = new BinaryFormatter();
			var stream = new MemoryStream(Convert.FromBase64String(serializedObject));

			var graph = formatter.Deserialize(stream) as ObjectGraph;

			return graph == null ? default(T) : (T) graph.CreateInstance(true);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
I'm a professional developer with over 9 years of experience in advanced C# development. I've worked extensively with every phase of the SDLC and have developed and deployed many enterprise solutions using the latest .Net technologies. Please let me know if you have any suggestions or questions.

Comments and Discussions