1

I'm pretty new to C#, so please excuse any questions which seem basic.

I'm wondering why TextWriter and StreamWriter can both serve the same function (or seem to) in my code example (working with an XML serialization method).

In this example, I'm playing around with a list of XML elements, attributes, etc., and hoping to serialize them by passing them into the serialize function (I have created) as a list.

Here's the code (notice the use of TextWriter):

public static void serialize(List<Table> listOfTables)
{
    var ser = new XmlSerializer(typeof(List<Table>));

    TextWriter writer =
        new StreamWriter(@"Location\Sample.xml");

    ser.Serialize(writer, listOfTables);
    writer.Close();
}

And here's the code which works exactly the same (or so it seems) (notice the use of StreamWriter instead of TextWriter):

public static void serialize(List<Table> listOfTables)
{
    var ser = new XmlSerializer(typeof(List<Table>));

    StreamWriter writer =
        new StreamWriter(@"Location\Sample.xml");

    ser.Serialize(writer, listOfTables);
    writer.Close();
}

As I'm pretty new, I understand the basics of inheritance and abstract classes, but I can't seem to join all the pieces together in order to fully comprehend this.

Please send your thoughts and suggestions. Thanks!

Sam
  • 2,935
  • 1
  • 19
  • 26

1 Answers1

2

Both instances are StreamWriter instances, but one instance you assign to a variable of the base class type TextWriter, which is okay.

Since XmlSerialize.Serialize has an overload that accepts an instance of the base class TextWriter, both calls are okay and have the same net effect.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325