Reputation: 6980
Is there some way to directly pass in a variable to a lambda method?
For example
string s = "test";
new Thread(() => MessageBox.Show(s)).Start();
Lambda expressions really make life so much easier for me, why does it seem so complicated to pass a variable in from the outside world?
Upvotes: 0
Views: 886
Reputation: 37770
How can I accomplish this with 1 semicolon?
What's the problem?
new Thread(() => MessageBox.Show("test")).Start();
Upd.
the easiest way to pass something to lambda is a closures (this is how your question looks). That's why they are so convenient. By passing parameters like shown here, you're destroying all preferences of lambdas. This should be clear for you from your next question about passing two or more parameters.
Using closures, you can do this easily:
// somewhere in the code
var owner = // ...
var text = // ...
var caption = // ...
// here's the closures:
new Thread(() => MessageBox.Show(owner, text, caption)).Start();
Without them you need to get (or make) some type, which will be a container for your parameters, create instance of that type and initialize it members. Indeed, this is the work compiler does for you, when you're using closures. So, why do you prevent the compiler to do all this dirty job?
Upvotes: 1
Reputation: 38
Hi for parameterized thread write code like below
string a = "test";
new Thread((s) => { s = "newTest"; }).Start(a);
Upvotes: 1
Reputation: 10422
Yes, there are many ways to do it. Like
string s = "test";
new Thread((string parameter) => MessageBox.Show(s)).Start();
for more details see ......first 2nd third
Upvotes: 0
Reputation: 4168
It isn't really complicated, especially if you're using the method-group syntax:
new Thread(MessageBox.Show).Start("test");
Upvotes: 2
Reputation: 707
Lambda expressions can take parameters as follows:
(string s) => MessageBox.Show(s);
This would change the definition of the action, so the method accepting the lambda needs to be able to accept the new delegate.
See the msdn document for further explanation.
Upvotes: 1