MS Exam 70-536 Prep: Efficient use of TextWriter - The practice test answer is wrong (I think)!
I'm taking a practice test for the exam 70-536. Below is a screens开发者_如何学Gohot. 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 existingStream
object, such as an instance ofFileStream
.
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????
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");
}
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.
精彩评论