Skip to content

Instantly share code, notes, and snippets.

@sheva29
Created July 5, 2017 21:20
Show Gist options
  • Save sheva29/9d21e45cdb331a81ad0d77ff8ac054d4 to your computer and use it in GitHub Desktop.
Save sheva29/9d21e45cdb331a81ad0d77ff8ac054d4 to your computer and use it in GitHub Desktop.
Converting obj to same type
private static T ConvertType<T>(object instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
var typeSource = instance.GetType();
var typeDestination = typeof(T);
T result = default(T);
// We're using a Memorystream for the serialization magic
using (var ms = new MemoryStream())
{
// Create the serializer for the incoming type
var serializer = new XmlSerializer(typeSource);
// Create a XML text writer, and serialize the incomming instance to memory
var tw = new XmlTextWriter(ms, Encoding.UTF8);
serializer.Serialize(tw, instance);
// Rewind the MemoryStream to the beginning.
ms.Position = 0;
// Now, create the deserializer for the destination type
var deserializer = new XmlSerializer(typeDestination);
using (var reader = new XmlTextReader(ms))
{
try
{
result = (T)deserializer.Deserialize(reader);
}
catch (Exception ex)
{
throw new ApplicationException(String.Format("Converting from type: {0}->{1} failed", typeSource.FullName, typeDestination.FullName), ex);
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment