I'd like to write a method that takes a string parameter -- say, sLastName
-- and returns a very simple Func<string>
that has captured that variable and simply returns it. This doesn't work...
Func<string> MyMethod (string myStringVar)
{
return () => myStringVar;
}
...in that if sLastName
is "Smith"
, and I call MyMethod(sLastName).Invoke()
, I'll get back "Smith"
; but if I then set sLastName
to "Jones"
and call MyMethod
again, I'll still get back "Smith"
.
So, to make using MyMethod
as simple as possible, I'd like to be able to pass sLastName
in as a string, and then (assuming sLastName
has been declared, is in scope, etc.), by somehow leveraging the Expression
class, return a Func<string>
with sLastName
embedded as a captured variable... like so...
MyMethod("sLastName").Invoke()
...and it would return the current value of sLastName
. But I can't see any way of using strings to build Expressions, and haven't yet found such in StackOverflow. Any way to do this?
Thanks in advance! (By the way, I know I can just create the lambda on the fly and pass it in as a parameter; just looking for something even simpler, where I can use only the name of the variable.)