In C #, why can't I pass a StringReader to a method with a Stream parameter?

In .net 4 and C #. I applied a static method to deserialize an XML stream into an object. This is only one XML format that goes into one object, so I am not trying to do anything with this. Since I can get this XML content in various ways, I decided that I passed the parameter to the static method of the Stream object. I thought that then it would take any object obtained from the Stream base class - like FileStream, MemoryStream, StringReader, etc.

It works fine when I pass it a FileStream object, but not when I pass it a StringReader.

My static method:

public static MatchObj DeserializeMatch(Stream srXml) { XmlSerializer xs = new XmlSerializer(typeof(MatchObj)); MatchObj mObj = (MatchObj)xs.Deserialize(srXml); return mObj; } 

It works with FileStream:

  MatchObj objReply; using (FileStream fs = new FileStream(Server.MapPath("/App_Data/Match.xml"), FileMode.Open)) { objReply = MStatic.DeserializeMatch(fs); fs.Close(); } 

But not StringReader:

 StringReader sr = new StringReader(Request.Form["mXML"]); MatchObj objReply = MStatic.DeserializeMatch(sr); 

Build error: "cannot convert from" System.IO.StringReader "to" System.IO.Stream "

Which in itself makes sense, but I thought that since StringReader implements TextReader, is it considered Stream? XML Deserializer works great with any of them.

I worked on it simply by overloading this method to take a StringReader, but I don't like to see that I thought the elegant idea was falling apart. Any ideas on why this is not working, and / or a way to make it work?

+4
source share
3 answers

Here is the StringReader inheritance hierarchy ...

  System.object 
   System.MarshalByRefObject
     System.IO.TextReader
       System.IO.StringReader

I would suggest putting Request.Form ["mXML"] in a MemoryStream.

This may work (not verified) ...

 var xmlBytes = Encoding.UTF8.GetBytes(Request.Form["mXML"]); var ms = new MemoryStream(xmlBytes); var reply = MStatic.DeserializeMatch(ms); 
+7
source

Well, technically (but obviously), because neither StringReader nor TextReader get out of Stream .
Perhaps more informatively, Stream is an abstract base class that represents a sequence of bytes. All classes [Something]Reader and [Something]Writer are designed to read or write to / from Stream , they themselves are not Stream objects. It may be true, however, that these classes are very poorly named and contribute to the misunderstandings that many developers have about this whole topic.

+4
source

TextReader is also not a stream, it inherits directly from MarshalByRefObject: http://msdn.microsoft.com/en-us/library/system.io.textreader.aspx

+1
source

All Articles