Une ligne pour Si la chaîne n’est pas nulle ou vide

J’utilise habituellement quelque chose comme ça pour diverses raisons tout au long d’une application:

if (Ssortingng.IsNullOrEmpty(strFoo)) { FooTextBox.Text = "0"; } else { FooTextBox.Text = strFoo; } 

Si je vais l’utiliser beaucoup, je créerai une méthode qui renvoie la chaîne souhaitée. Par exemple:

 public ssortingng NonBlankValueOf(ssortingng strTestSsortingng) { if (Ssortingng.IsNullOrEmpty(strTestSsortingng)) return "0"; else return strTestSsortingng; } 

et l’utiliser comme:

 FooTextBox.Text = NonBlankValueOf(strFoo); 

Je me suis toujours demandé s’il y avait quelque chose qui faisait partie de C # qui le ferait pour moi. Quelque chose qui pourrait être appelé comme:

 FooTextBox.Text = Ssortingng.IsNullOrEmpty(strFoo,"0") 

le deuxième paramètre étant la valeur renvoyée si Ssortingng.IsNullOrEmpty(strFoo) == true

Si ce n’est pas le cas, quelqu’un a-t-il de meilleures approches?

Il y a un opérateur de coalescence nul ( ?? ), mais il ne gère pas les chaînes vides.

Si vous étiez uniquement intéressé par les chaînes NULL, vous l’utiliseriez comme

 ssortingng output = somePossiblyNullSsortingng ?? "0"; 

Pour votre besoin spécifique, il y a simplement l’opérateur conditionnel bool expr ? true_value : false_value bool expr ? true_value : false_value que vous pouvez utiliser pour simplement si / else les blocs d’instructions qui définissent ou renvoient une valeur.

 ssortingng output = ssortingng.IsNullOrEmpty(someSsortingng) ? "0" : someSsortingng; 

Vous pouvez utiliser l’ opérateur ternaire :

 return ssortingng.IsNullOrEmpty(strTestSsortingng) ? "0" : strTestSsortingng FooTextBox.Text = ssortingng.IsNullOrEmpty(strFoo) ? "0" : strFoo; 

Vous pouvez écrire votre propre méthode d’ extension pour le type Ssortingng: –

  public static ssortingng NonBlankValueOf(this ssortingng source) { return (ssortingng.IsNullOrEmpty(source)) ? "0" : source; } 

Maintenant, vous pouvez l’utiliser comme avec n’importe quel type de chaîne

 FooTextBox.Text = strFoo.NonBlankValueOf(); 

Cela peut aider:

 public ssortingng NonBlankValueOf(ssortingng strTestSsortingng) { return Ssortingng.IsNullOrEmpty(strTestSsortingng)? "0": strTestSsortingng; } 

Ancienne question, mais pensais que je l’appendais pour aider,

 #if DOTNET35 bool isTrulyEmpty = Ssortingng.IsNullOrEmpty(s) || s.Trim().Length == 0; #else bool isTrulyEmpty = Ssortingng.IsNullOrWhiteSpace(s) ; #endif