How to serialize a Object to XML in C# and VB.NET

To serialize a Object to XML in C# and VB.NET you can use the following snippet.

Sample C#

public static string Serialize<T>(T toSerialize)
{
	var xmlSerializer = new XmlSerializer(toSerialize.GetType());
	var stringWriter = new StringWriter();
	xmlSerializer.Serialize(stringWriter, toSerialize);
	return stringWriter.ToString();
}

Sample Vb.NET

Public Shared Function Serialize(Of T)(toSerialize As T) As String
	Dim xmlSerializer = New XmlSerializer(toSerialize.GetType())
	Dim stringWriter = New StringWriter()
	xmlSerializer.Serialize(stringWriter, toSerialize)
	Return stringWriter.ToString()
End Function

Please Share us:
Please rate this snippet

One thought on “How to serialize a Object to XML in C# and VB.NET

Leave a Reply