tom redfern
tom redfern

Reputation: 31750

C# type assignment and method call in single statement

I have this:

var doc = new XmlDocument();
doc.LoadXml("<XMLHERE/>"); //This returns void

How do I combine into one statement?

Upvotes: 1

Views: 282

Answers (6)

musefan
musefan

Reputation: 48415

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

Upvotes: 2

Despertar
Despertar

Reputation: 22362

Use static XDocument.Parse(string xml) which returns an XDocument object;

    XDocument doc = XDocument.Parse("<XMLHERE/>");

Upvotes: 5

Grant Thomas
Grant Thomas

Reputation: 45083

You 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.

Upvotes: 4

Piotr Auguscik
Piotr Auguscik

Reputation: 3681

You can write extension:

public static XmlDocument MyLoad(this XmlDocument doc, string xml)
{
    doc.LoadXml(xml);
    return doc;
}

Usage:

var doc = new XmlDocument().MyLoad(xml); 

Upvotes: 1

Moha Dehghan
Moha Dehghan

Reputation: 18443

You cannot. If defining the variable does not count as a statement, you can write:

XmlDocument doc;
(doc = new XmlDocument()).LoadXml("<XMLHERE/>");

Upvotes: 1

JaredPar
JaredPar

Reputation: 754575

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/>");

Upvotes: 1

Related Questions