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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Apr 5, 2011, 9:40 AM EDT
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.
Posted Apr 5, 2011, 9:49 AM EDT
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?
VulpesRank #55 · 29.2K reputationPosted Apr 5, 2011, 10:03 AM EDT
VulpesRank #55 · 29.2K reputationPosted Apr 5, 2011, 10:30 AM EDT
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;