You can avoid all of this by using the explicit cast operators:
public XElement Element
{
set
{
this.MyVar1 = (string)value.Element("MyVar1") ?? "NO VALUE";
this.MyVar2 = (string)value.Element("MyVar2") ?? "NOVAL";
}
}
Both
XElement
and
XAttribute
define explicit cast operators for:
string,<br />
bool, bool?, <br />
int, int?, <br />
long, long?, <br />
uint, uint?, <br />
ulong, ulong?, <br />
float, float?, <br />
double, double?, <br />
decimal, decimal?, <br />
DateTime, DateTime?, <br />
DateTimeOffset, DateTimeOffset?, <br />
TimeSpan, TimeSpan?, <br />
Guid, Guid?
For string and nullable value types, the operators simply return null if the element or attribute is null; for non-nullable value types, they throw an
ArgumentNullException
for null elements or attributes.