user10025519
user10025519

Reputation: 83

How to properly initialize a lambda expression's parameter where the lambda is a method parameter?

I have found an example here https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-3.1&tabs=windows:

            static void Main(string[] args)
            {
                var host = new HostBuilder();
                host.ConfigureAppConfiguration((hostContext, builder) =>
                 {
                    // Add other providers for JSON, etc.

                    if (hostContext.HostingEnvironment.IsDevelopment())
                     {
                         //builder.AddUserSecrets<Program>();
                     }
                 })
                 .Build();
            }

When this code starts in debugging mode the hostContext and builder variables already have some values. How I can write my own method in this way like the described above? E.g. when I pass a lambda expression as a parameter to my method then my class, that owns this method, can initialize the parameters of this lambda expression by some customized objects?

Upvotes: 1

Views: 116

Answers (1)

zaitsman
zaitsman

Reputation: 9509

The lambda here is simply an Action<T1, T2>

So you can write your method like so:

public static void DoMyWork(Action<Something, Else> action) {
   var something = new Something();
   var else = new Else();
   action(something, else);
}

And then call it like so:

MyClass.DoMyWork((something, else) => {
   Console.WriteLine($"{something} is not null and neither is {else}");
});

Upvotes: 4

Related Questions