? operator without else-part

后端 未结 3 1714
死守一世寂寞
死守一世寂寞 2020-12-11 00:05

I use C# ? operator when I have if-statements that affects one row and it\'s all good. But lets say I have this code (using classic if-statements):

if(someSt         


        
3条回答
  •  生来不讨喜
    2020-12-11 00:16

    Some background: we use constructs like this a lot:

    sql = "SELECT x FROM table WHERE Y " + (condition ? " AND Column = 1" : "");
    

    We also use constructs like this in Razor views

    The : "" is pretty annoying so we built an extension method

    public static T Then(this bool value, T result)
    {
        return value ? result : default(T);
    }
    

    Usage:

    taken from here

提交回复
热议问题