MS Exam 70-536 Prep: Efficient use of TextWriter - The practice test answer is wrong (I think)!

StackOverflow https://stackoverflow.com/questions/6004940

  •  14-11-2019
  •  | 
  •  

Question

I'm taking a practice test for the exam 70-536. Below is a screenshot. The yellow highlighted is what the exam says is the correct answer. The one with the radio button selected is the answer I thought it was.

Note the explanation at the bottom which includes the statement:

To create a StreamWriter object, you must use an existing Stream object, such as an instance of FileStream.

I think the answer I chose is the most efficient use and I think the statement made in the explanation is wrong. Clearly, because the code in my selected answer worked fine.

Who's right????

enter image description here

Was it helpful?

Solution

In the answer you choose there's a difference between the C# and VB.NET version. The VB.NET version won't even compile whereas the C# is correct.

This won't compile:

Dim tw as TextWriter = New FileStream("Hello.dat", FileMode.Create)

This is OK:

TextWriter tw = new StreamWriter("Hello.dat");

The last answer is out of the question because TextWriter is an abstract class and you cannot instantiate it directly.

But obviously the correct answer which is what you would use in a real world application is not even present in the list. It would be:

using (var writer = new StreamWriter("Hello.dat"))
{
    writer.Write("Hello world");
}

or if you need to use a Stream:

using (var stream = File.Create("Hello.dat"))
using (var writer = new StreamWriter(stream))
{
    writer.Write("Hello world");
}

OTHER TIPS

They're right - you can't set a TextWriter equal to an instance of FileStream as FileStream does not inherit from TextWriter - you need to use a StreamWriter based on the FileStream as StreamWriter does inherit from TextWriter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top