Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a method with the following signature:

private PropertyInfo getPropertyForDBField(string dbField, out string prettyName)

In it, I find the associated value prettyName based on the given dbField. I then want to find all properties, if any, that have the name prettyName, so I'm trying to do the following:

IEnumerable<PropertyInfo> matchingProperties =
    getLocalProperties().Where(prop =>
        prop.Name.Equals(prettyName)
    );

However, this gives the following error:

Cannot use ref or out parameter 'prettyName' inside an anonymous method, lambda expression, or query expression

By the point in the method where I'm trying to use prettyName in the Where lambda parameter, prettyName is definitely initialized. I return if prettyName cannot be initialized to a valid value. Is there some trick I could do here to let me use prettyName in the lambda expression?

Edit: I'm using .NET 3.5 if it matters.

like image 840
Sarah Vessels Avatar asked Oct 28 '10 18:10

Sarah Vessels


2 Answers

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.

like image 178
Lee Louviere Avatar answered Nov 13 '22 22:11

Lee Louviere


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.

like image 20
Ani Avatar answered Nov 13 '22 21:11

Ani