Reputation: 4848
I have the following code:
// TryGetAttributeValue returns string value or null if attribute not found
var attribute = element.TryGetAttributeValue("bgimage");
// Convert attribute to int if not null
if (attribute != null) BgImage = convert.ToInt32(attribute);
The thing I don't like is that I have to create a temp variable, attribute
, in order to test if it's null
or not, and then assign the value to the BgImage
variable, which is a nullable int.
I was hoping I could figure out a way to write it all on one line, but I cannot figure a way. I even tried using a ternary statement, but got nowhere:
if (element.TryGetAttributeValue("bgimage") != null) ? BgImage = //Convert result to int : else null;
Realistically, my original two lines of code do the job. I was just hoping to pare it down to one line. But, if anyone knows how to do what I'm trying to accomplish, I'd love to learn how.
Upvotes: 3
Views: 122
Reputation: 82096
Assuming TryGetAttributeValue
returns a string
you could do something like
BgImage = convert.ToInt32(element.TryGetAttributeValue("bgimage") ?? "-1")
This would set BgImage
to a default value (-1
) if the attribute does not exist. If you would prefer to have BgImage
set to null
when there is no bgimage
attribute then it gets a little bit clunkier
BgImage = element.TryGetAttributeValue("bgimage") != null ?
convert.ToInt32(element.TryGetAttributeValue("bgimage")) : (int?)null;
Upvotes: 2
Reputation: 236208
I recommend you to use Linq to Xml for parsing Xml (according to your attempt you have BgImage as nullable integer):
BgImage = (int?)element.Attribute("bgimage");
You also can assign some default value if BgImage is not nullable:
BgImage = (int?)element.Attribute("bgimage") ?? 0;
Upvotes: 3