65.9K
CodeProject is changing. Read more.
Home

Using Extension Methods To Avoid XML Problems

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (3 votes)

Jan 25, 2011

CPOL
viewsIcon

9569

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

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, bool, bool?, int, int?, long, long?, uint, uint?, ulong, ulong?, float, float?, double, double?, decimal, decimal?, DateTime, DateTime?, DateTimeOffset, DateTimeOffset?, TimeSpan, TimeSpan?, 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.