Reputation: 93
How to Convert var to string? In my windowsphone application page, i want to convert this var DemoHeader to a string.
XDocument myData = XDocument.Load("aarti.xml");
var DemoHeader = from query in myData.Descendants("bookinfo")
select new HeaderT
{
Header = (string)query.Element("header")
};
ContentHeaderLine.Text = DemoHeader.ToString(); //LINE GIVING WRONG DATA
public class HeaderT
{
string header;
public string Header
{
get { return header; }
set { header = value; }
}
}
How can i convert var DemoHeader to a string?
Upvotes: 1
Views: 5279
Reputation: 460138
First, var
is not a type by itself, the type will be inferred from the value by the compiler. Your type is actually HeaderT
and your query returns an IEnumerable<HeaderT>
(so possibly multiple).
Presuming you want the first header:
HeaderT first = DemoHeader.First();
string firstHeader = first.Header();
or you want all returned separated by comma:
string allHeaders = String.Join(",", DemoHeader.Select(dh => dh.Header()));
If you want that ToString
returns something meaningful(instead of name of the type), override it:
public class HeaderT
{
private string header;
public string Header
{
get { return header; }
set { header = value; }
}
public override string ToString()
{
return Header;
}
}
Upvotes: 3
Reputation: 334
Override ToString() in HeaderT class could help. After that, you DemoHeader variable is a list of HeaderT not a single HeaderT.
Upvotes: 0