Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

Using Extension Methods To Avoid XML Problems

, 25 Jan 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Richard Deeming
Software Developer Nevalee Business Solutions
United Kingdom United Kingdom
No Biography provided
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralBut the code is much simpler with the explicit cast operator... PinmemberRichard Deeming25-Jan-11 11:05 
GeneralUsing extension methods, I a) don't have to worry about null... PinmvpJohn Simmons / outlaw programmer25-Jan-11 11:02 
GeneralRe: But the code is much simpler with the explicit cast operator... PinmemberRichard Deeming25-Jan-11 11:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 25 Jan 2011
Article Copyright 2011 by Richard Deeming
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid