Here's what I want to do:
XmlWriter writer = XmlWriter.Create(
(string.IsNullOrEmpty(outfile) ? Console.Out : outfile)
);
This does not compile, however, giving the error "Type of conditional expression cannot be determined because there is no implicit conversion between 'System.IO.TextWriter' and 'string'". The above code is a simplification of the following:
XmlWriter writer;
if (string.IsNullOrEmpty(outfile))
{
writer = XmlWriter.Create(Console.Out); // Constructor takes TextWriter
}
else
{
writer = XmlWriter.Create(outfile); // Constructor takes string
}
These two calls to Create
are perfectly valid, and this compiles. Is there a way to make this more compact, like I was trying to do with my inline test?
It doesn't make sense to me that what I want doesn't work. Mentally thinking through this, it seems like the compiler would evaluate string.IsNullOrEmpty(outfile)
to determine which case to take:
- If the condition were true, it would go with
Console.Out
, and then see that it needs to polymorphically choose the version ofXmlWriter.Create
that takes a TextWriter. - If the condition were false, it would go with
outfile
, and then see that it needs to polymorphically choose the version ofXmlWriter.Create
that takes a string.
Has programming in ML warped my brain?