Edit: Given the edited question, this is much simpler.
Again it uses an extension method, but now there's no need to do a conversion in the method.
var myVariable = ParseNDecimal(xml.Element("myElement").ValueOrDefault("0"));
...
public static string ValueOrDefault(this XElement element,
string defaultValue)
{
return element != null ? element.Value : defaultValue;
}
If you don't like the method taking a string parameter, you could make it take object
and call ToString
, then call it like this:
var myVariable = ParseNDecimal(xml.Element("myElement").ValueOrDefault(0m));
However, that feels a little bit wrong to me. It assumes that the parsing will be the reverse of ToString
formatting.
Original answer
There's nothing particularly in the language to help you. (I'm not sure that you've got the exact code right - don't you mean something with an XAttribute
?) I'd suggest writing a utility method:
var myVariable = xml.Element("myElement").ValueOrDefault(0m);
...
public static decimal ValueOrDefault(this XElement element,
decimal defaultValue)
{
return element != null ?(decimal) element.Value : defaultValue;
}
If you adjust the code in the question, I'll do likewise for the code here. I suspect you did mean to use XAttribute
, which leads to a problem with generics - I haven't written the above in a generic way, because I believe you will want to call the XAttribute
"conversion to decimal" operator. A generic cast won't do that, as it doesn't know what kind of conversion you want at compile time. You can, however, overload the above method for all the result types you're interested in.