Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I refactor these two lines to one statement?

Tags:

c#

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.

like image 898
Kevin Avatar asked Dec 22 '25 15:12

Kevin


1 Answers

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;
like image 57
Sergey Berezovskiy Avatar answered Dec 24 '25 04:12

Sergey Berezovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!