1

I want to send an object to a parameter using a lambda expression.

If I have a Settings class like so:

public class Settings() {
    public string Name {get;set;}
    public string Whatever {get;set;}
}

And some other method whose argument is a Settings class:

public object GenerateIt(Settings settings) {
    // stuff here
}

I want to call it like so:

myObject.GenerateIt(
    s => {
        s.Name = "this";
        s.Whatever = "whatever";
    }
)

I've tried this but it doesn't quite do the trick:

public object GenerateIt(Func<Settings> settings) { ... }

I'm also trying (per current answers) using an Action:

public object GenerateIt(Action<Settings> settings) { ... }

... which allows me to (apparently) call the method in the way I'd prefer, but I can't seem to find out how to access those settings that I pass in?

public object GenerateIt(Action<Settings> settings) {

    Console.WriteLine(settings.Name);   // nope

    var s = settings(); // nope

    ??? 
}

(and yes, I did consult the documentation - if it were clear to me after that, I wouldn't still be asking)

What's the correct mechanism to allow for passing the object as indicated in the "I want to call it like so" example? Thanks

jleach
  • 7,410
  • 3
  • 33
  • 60

2 Answers2

4

Read the documentation.

Func<T> returns a T and takes no parameters. You want Action<T>.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • please see the question update... how do I then use the setting object from within the target method? – jleach Sep 11 '16 at 15:19
  • @jdl134679 you can call it like `var s = new Settings(); settings(s);` and `s` will contain your properties set. – serhiyb Sep 11 '16 at 15:23
  • I see... create a new variable, pass that to the Action, and the action fills the variable accordingly. That works, thanks – jleach Sep 11 '16 at 15:26
1
public object GenerateIt(Action<Settings> settings) { ... }

Read more on Action, Func, Predictate here: Delegates: Predicate Action Func

Update: Not sure what you are trying to archive, but try this.

enter image description here

Community
  • 1
  • 1
Cù Đức Hiếu
  • 5,569
  • 4
  • 27
  • 35
  • How do then I use `settings` within the body of that method? With `Func`, I'd say `Settings s = settings.Invoke()`, then use the `s` variable to access what I passed... can't seem to find how with to do that with an `Action` – jleach Sep 11 '16 at 15:08