Can the following code be translated into using the... ejem... 'using' statement?
TextReader TheReader;
if( UploadedFile ) { TheReader = new System.IO.StreamReader( LocalFileName ); }
else { TheReader = new System.IO.StringReader( Input ); }
//Use The reader
TheReader.Close();
So using (TextReader TheReader = ??)
Well you could use the conditional operator:
// Variable names changed for convention, and fully-qualified names simplified
using (TextReader reader = uploadedFile ? File.OpenText(localFileName)
: (TextReader) new StringReader(input))
{
...
}
The cast to TextReader
can be on either of the last two operands - it's just to let the compiler know the type of the expression, as it can't just find the common type (TextReader
) from StreamReader
(the 2nd operand) and StringReader
(the third).
You could assign the variable before the using
statement as per Guffa's answer - but personally I'd use this code, to keep the scope of the variable limited to the using
statement.
See more on this question at Stackoverflow