ojhawkins
ojhawkins

Reputation: 3278

Action<T> assign value to variable

I have an action

Action<string> removeTitle = source => { source = RemoveTitle(source); };

Which I invoke

string name = "MR JOHN DOE"
removeTitle(name);

But does not change the variable name

VS (possibly Resharper) said "Value assigned is not used in any execution path" for source after the lambda separator.

What am I doing wrong here?

Upvotes: 2

Views: 7445

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

You can capture name variable in Action... delegate and change it if it work in your particular context:

string name = "something";
Action<string> removeTitle = source => { name = RemoveTitle(source); };

removeTitle(name);

I would recommend to go with Func<string, string> as suggested by Simon Whitehead's answer if it is possible as code that does not capture local variable and just returns result without side effects is easier to reason about:

Func<string,string> removeTitle = RemoveTitle;  
name = removeTitle(name);

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65059

Strings are immutable.. so your reference is being re-created within the scope of the lambda. It is a similar issue to this question.

You need to return it via a Func<T1, T2> delegate if you want to modify it, but you can't use ref or out (as suggested in that question) unless you create your own delegate type (Note: I have shortened it via method grouping):

Func<string, string> removeTitle = RemoveTitle;

// ...
name = removeTitle(name);

Upvotes: 4

Related Questions