Why can't we define a variable inside an if statement?

前端 未结 5 1066
余生分开走
余生分开走 2020-12-01 04:13

Maybe this question has been answered before, but the word if occurs so often it\'s hard to find it.

The example doesn\'t make sense (the expression is

5条回答
  •  情歌与酒
    2020-12-01 05:01

    C# 7.0 introduced ability to declare out variables right inside conditions. In combination with generics, this can be leveraged for the requested result:

    public static bool make (out T result) where T : new() {
        result = new T();
        return true;
    }
    // ... and later:
    if (otherCondition && make(out var sb)) {
        sb.Append("hello!");
        // ...
    }
    

    You can also avoid generics and opt for a helper method instead:

    public static bool makeStringBuilder(out StringBuilder result, string init) {
        result = new StringBuilder(init);
        return true;
    }
    // ... and later:
    if (otherCondition && makeStringBuilder(out var sb, "hi!")) {
        sb.Append("hello!");
        // ...
    }
    

提交回复
热议问题