Hi,
How is the following possible without creating an instance\object of the TextWriter class and and then an instance\object of the StreamReader class?
TextWriter tw = new StreamReader();
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Apr 5, 2011, 1:40 PM
TextWriter tw = new StreamWriter("myfile.txt");
As StreamWriter inherits from the abstract class TextWriter, we can assign a reference to a StreamWriter object to a TextWriter variable.
There's always an implicit conversion from a derived class to its base class. Notice though that you'll only be able to access those members of StreamWriter which it inherits from TextWriter via the 'tw' reference.
VulpesPosted Apr 5, 2011, 2:30 PM
When you're using the assignment operator '=', then - yes -you should read it from right to left.
In fact, this is perfectly legal:
int x, y, z;
x = y = z = 42;
As you might guess, this sets all 3 variables to 42.
The first operation is:
z = 42;
Now this assignment statement is also regarded as an expression which has a value of 42 (i.e the value of the RHS).
The next operation is:
y = z;
which again is regarded as an expression with a value of 42, and the final operation (the end of the chain) is:
x = y;
VulpesPosted Apr 5, 2011, 2:03 PM
Posted Apr 5, 2011, 1:49 PM
I did mean TextWriter tw = new StreamWriter("myfile.txt"); apologies!
Ive never come across any code with a syntax like this?
Is it another way of creating an instance of a class?