2016-04-29 1 views
6

あなたがラッシュについて考える前に? null合体演算子:1の線形、美しさとC#でnullの場合に値を割り当てるクリーンな方法は?

string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null"; 

myParentまたはobjPropertyがnullであるかどうか、それもstrPropertyの評価に到達する前に例外がスローされますとき、ここで問題があります。

次の余分なヌルcheckingsを避けるために:

if (myParent != null) 
{ 
    if (objProperty!= null) 
    { 
     string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null"; 
    } 
} 

私は、一般的にこのようなものを使用します。

string result = ((myParent ?? new ParentClass()) 
       .objProperty ?? new ObjPropertyClass()) 
       .strProperty ?? "default string value if strObjProperty is null"; 

オブジェクトがnullであれば、それが唯一のことができるようにするために、新しいものを作成し、プロパティにアクセスします。

非常にきれいではありません。

私は '???'演算子:

string result = (myParent.objProperty.strProperty) ??? "default string value if strObjProperty is null"; 

...代わりにデフォルト値を返すためにかっこの内部から "null"が残っていても問題ありません。

あなたのヒントありがとうございます。

+4

ルック:IfNullOrEmptyだけである

string result = (myParent?.objProperty?.strProperty) .IfNullOrEmpty("default string value if strObjProperty is null"); 

を。 – Luaan

答えて

11

C#6に付属するヌル伝播演算子はどうなりますか?

string result = (myParent?.objProperty?.strProperty) 
       ?? "default string value if strObjProperty is null"; 

はnullのためmyParentobjPropertystrPropertyをチェックし、それらのいずれかがnullの場合、デフォルト値を割り当てます。

私も空をチェックする拡張メソッドを作成することで、この機能を拡張しています:?C#6、 `.`オペレータで

public static string IfNullOrEmpty(this string s, string defaultValue) 
{ 
    return !string.IsNullOrEmpty(s) ? s : defaultValue); 
} 
+0

まさに!私はそのような特徴を長く待っていた;) – renzol

関連する問題