I have this:
var doc = new XmlDocument();
doc.LoadXml("<XMLHERE/>"); //This returns void
How do I combine into one statement?
Use static XDocument.Parse(string xml) which returns an XDocument object;
XDocument doc = XDocument.Parse("<XMLHERE/>");
var foo = XDocument.Load(new MemoryStream(Encoding.UTF8.GetBytes("<xml />"))); The overload of static member of XDocument Load that accepts string as a parameter expects URIYou can't, lest you lose the reference to the document (doc) and therefore find it to be inaccessible.
As other answers have began filtering in to contradict my assertion, what I will say is this. Of course, you can create a method to do 'the dirty work' for you, but then you're not really just turning this into a one-liner, you're just disjointing the creation (and not really saving unless you need to write this in hundreds of different places).
This might not be a bad thing in many situations, but defining a class with a single extension method to facilitate this seems ridiculous. Specifying it locally, within a class where this would be extensively utilised could be a different matter.
All in all, my answer still stands fundamentally, not considering the many contrived ways you might 'get around' this.
this is probably your best (alternative to two lines) option...
public static XmlDocument MyLazyAssFunction(xml)
{
var doc = new XmlDocument();
doc.LoadXml(xml);
return doc;
}
then here is your single statment...
var doc = MyLazyAssFunction("<XMLHERE/>");
The point here being that your original two lines is a perfectly fine way of doing what you need to do.. and it is very readable as it stands too
return doc.With just the XmlDocument API you can't do this in a single line and keep the XmlDocument reference. However you could write a helper API
public static class XmlUtils {
public static XmlDocument CreateDocument(string xml) {
var doc = new XmlDocument();
doc.LoadXml(xml);
return doc;
}
}
var doc = XmlUtils.CreateDocument("<XMLHERE/>");
new Action(() => { var doc = new XmlDocument(); doc.LoadXml("XML"); }).Invoke();Almost single statement ))new Action<XmlDocument>((x) => x.Load("Your xml"))(new XmlDocument());