Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
C#
public class SerializeManager<T> {
	public string SerializeObject(T pObject) { 
		string XmlizedString = null; 
		MemoryStream memoryStream = new MemoryStream(); 
		XmlSerializer xs = new XmlSerializer(typeof(T)); 
		XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); 
		xs.Serialize(xmlTextWriter, pObject); 
        //???-------here---------???//
		memoryStream = (MemoryStream)xmlTextWriter.BaseStream; 

		XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); 
		return XmlizedString; 
	} 


I just don't understand about this line:
C#
memoryStream = (MemoryStream)xmlTextWriter.BaseStream


in my opinion,because he has specified memoryStream in XmlTextWriter constuctor.
that is only a redundancy.

really?
Posted
Comments
Andy Lanng 24-Aug-15 8:59am    
test it, but yes, I agree with you. It is redundant

XmlTextWriter.BaseStream is of type Stream.

While MemoryStream inherits Stream and 'is' Stream for this purpose, it is still good idea to explicitly cast it, if for no other reason then readability.

Also, you get a warning in the output (or even error if you have treat warnings as errors turned on)
 
Share this answer
 
It is required. You passed a MemoryStream into the constructor but that is stored as "Stream", in other words it is down-casted from MemoryStream to Stream. Likewise the BaseStream returns type Stream. Even though the object BaseStream returns is MemoryStream, you have to "up cast" it back to MemoryStream as you know it is a memory stream. Without casting it back to MemoryStream you won't have access to ToArray, as that is not on the underlying Stream class. Also without the explicit cast the code won't compile as you can't implicitly convert from from Stream to MemoryStream. These are fairly standard inheritance-based issues. You see less of these issues when dealing with classes that support generics as you're always dealing with the correct types.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900