C# - how to pass 'out' parameter into lambda expression

前端 未结 2 999
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 12:20

I have a method with the following signature:

private PropertyInfo getPropertyForDBField(string dbField, out string prettyName)

In it, I fi

相关标签:
2条回答
  • 2020-12-10 12:49

    Just to clarify. It's possible to use ref/out arguments from a called method in a lambda.

    You can also use a ref or out if you specify type of the parameter. Which means sending prettyName as a parameter to the lambda.

    (prop, ref string prettyName) => prop.Name.Equals(prettyName);
    

    Where clause takes in only one argument, which is the property element in the list. This is what prevents you from adding an argument to the lambda.

    Didn't want to leave people the false impression that you cannot use these arguments in a lambda. You just can't use them by capture.

    0 讨论(0)
  • 2020-12-10 13:12

    As the compiler error indicates, it isn't allowed to use out or ref parameters inside lambda expressions.

    Why not just use a copy? It's not like the lambda wants to mutate the variable anyway, so I don't see a downside.

    string prettyNameCopy = prettyName;
    var matchingProperties = getLocalProperties()
                            .Where(prop => prop.Name == prettyNameCopy);
    

    Alternatively, you can use a local throughout (to evaluate the appropriate name etc.), and assign the outparameter prettyName just before returning from the method. This will probably be more readable if there isn't significant branching within the method.

    0 讨论(0)
提交回复
热议问题