0

I have a class with a property that returns a function.

public class Demo
{
    public Func<string,int,bool> Something { get; set; }
}

If I do like this

Demo demo = new Demo();

string target;

demo.Something = (a,b)=>
{
   //in here `a` contains a value.
   //and I want to do:
   target = a;

   return true;
};


 //later in the code target is null
 //target here is null instead of having the value of `a`

How do I assign the value of a to target variable within the lambda to reuse it later in code?

user2818430
  • 5,853
  • 21
  • 82
  • 148
  • You're doing it correctly. However, `Something` isn't being invoked. You're simply defining the function. Writing `demo.Something(...)` afterwards would correctly assign `target` – Rob Nov 14 '16 at 22:31
  • @Rob: what do you mean by writing demo.Something() afterwards? Actually when I debug it I can see the value of `a` and is assigned to target variable. However after the delegate ends the target is null. – user2818430 Nov 14 '16 at 22:36
  • @user2818430, please show more of your code. You've omitted way too much. In particular, show the lines that invoke `demo.Something` and where you are checking for the value of `target`. Preferably your code should actually be runnable -- i.e. a minimal self-contained compilable example. – Kirk Woll Nov 14 '16 at 23:16
  • @user2818430 Your current code won't compile. `Demo.Something` only takes two arguments while you're initializing it as `(a, b, c)`. If you fix it to be `(a, b)` and then immediately write `demo.Something("Testing", 5); Console.WriteLine(target);` you'll see that target is indeed updated. Please show us the actual code you're testing (and make sure the code you post still exhibits the same behaviour) – Rob Nov 14 '16 at 23:20

1 Answers1

0
 public static void Main(string[] args)
 {
     Demo demo = new Demo();

     string target;

     demo.Something = (a, b) =>
     {
         target = a;
         return true;
     };

     //Call something with params
     demo.Something("foo", 1);
 }
Damian
  • 74
  • 5