TextWriter and StreamWriter

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
 
S

Stanimir Stoyanov \(C# MVP\)

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,
 
I

Ignacio Machin ( .NET/ C# MVP )

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top