TextWriter and StreamWriter

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

If I have this kind of statements what is the correct name for this
TextWriter object sw.
I use lateBinding as you can see.
I mean here this TextWriter object sw is used to create a StreamWriter
object. This sw object
is actually refering to a StreamWriter object
I could of course have used a StreamWriter like this instead
Here this sw object is actually a StreamWriter object

using(StreamWriter sw = new StreamWriter(new FileStream(fileName,
FileMode.Create)))
{
....
}


using (TextWriter sw = new StreamWriter(new FileStream(fileName,
FileMode.Create)))
{
sw.Write(txtBox.Text);
}

//Tony
 
In an essence, both are correct.

The StreamWriter class inherits from TextWriter, hence why you can use it
interchangeably in the using statement. Either is correct, but depending on
the case, one of them might be more suitable:

1) If you decide your application to make use of an interface class and thus
reduce the dependency on the actual StreamWriter class. This way you can
have any object that derives from TextWriter and use their common members.
In addition to this, code redundancy can be eliminated by reusing the
interface code. E.g.

using(TextWriter sw = Helpers.OpenForWriting(fileName))
{
// ...
}

2) Your first example is much easier to read and maintain as you (and any
other developers who might have to refactor your code) know at a first
glance what the type dependencies are.

HTH,
 
Hello!

If I have this kind of statements what is the correct name for this
TextWriter object sw.
I use lateBinding as you can see.
I mean here this TextWriter object sw is used to create a StreamWriter
object. This sw object
is actually refering to a StreamWriter object
I could of course have used a StreamWriter like this instead
Here this sw object is actually a StreamWriter object

using(StreamWriter sw = new StreamWriter(new FileStream(fileName,
FileMode.Create)))
{
...

}

using (TextWriter sw = new StreamWriter(new FileStream(fileName,
FileMode.Create)))
{
    sw.Write(txtBox.Text);
 }

//Tony

Hi,

TextWriter is an abstract class. StreamWriter inherit from it. that is
why your using statement above works.
 
Back
Top