Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I feel that every time I use TryParse that it results in somewhat ugly code. Mainly I am using it this way:

int value;
if (!int.TryParse(someStringValue, out value))
{
    value = 0;
}

Is there some more elegant solution for parsing all basic data types, to be specific is there a way to do fail safe parsing in one line? By fail safe I assume setting default value if parsing fails without exception.

By the way, this is for cases where I must do some action even if parsing fails, just using the default value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
314 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is valid and you may prefer it if you have a liking for single-liners:

int i = int.TryParse(s, out i) ? i : 42;

This sets the value of i to 42 if it cannot parse the string s, otherwise it sets i = i.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...