Alex Rivera | Logout

How do I return the first string variable that isn't null or empty

Asked 2010-03-29T15:45:31.663
33

If I have 5 String variables and between 0 and 5 of them are null or empty is there an easy/short way of returning the first one that is not null or empty? I am using .NET 3.5

Edit
Report

2 Answers

23

Define an extension method:

static string Or(this string value, string alternative) {
    return string.IsNullOrEmpty(value) ? alternative : value;
}

Now you can say the following:

string result = str1.Or(str2).Or(str3).Or(str4) …
answered 2010-03-29T15:48:04.210
1
var found = new[]{first, second, third, fourth, fifth}.FirstOrDefault(x =>!String.IsNullOrEmpty(x));
answered 2010-03-29T15:55:19.833

Your Answer