Can the new pattern matching syntax work with existing variables?

I have existing code:

    internal bool firstAsSymbol(out Symbol s)
    {
        return (s = first as Symbol) != null;
    }

I can use the new syntax is, but I need to enter local variables:

    internal bool firstAsSymbol(out Symbol s)
    {
        var result = first is Symbol sym;
        s = sym;
        return result;
    }

EDIT: Actually, the above code does not compile! symmay be undefined per line s = sym;. This is even worse: you need to use the instruction ifand assign sthen and else in the sentence. (He is trying to allow to symbe valid for a touch in the right section).

Is there a simpler alternative (apart from the source code, of course)?

+4
source share
2 answers

, , is T, , , .

out var. , , out var . is T , , .

: # 7, "out var" .

, , # 7, :

internal (bool, Symbol) FirstAsSymbol() =>
    first is Symbol sym ? (true, sym) : (false, null);

, , FirstAsSymbol, , .

+2

, :

exprs.firstAsSymbol(out var s)

:

exprs.first is Symbol s

EDIT: , : s == null, .

, firstIsSymbol: -)

+1

Source: https://habr.com/ru/post/1666375/


All Articles