jdl134679 jdl134679 - 2 months ago 11
C# Question

C# Accept Object Parameter via Lambda

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:

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


Read the documentation.

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