Home > Mobile >  Create an instance of an object using an Expression
Create an instance of an object using an Expression

Time:09-02

I have this class

public class TableSettings
{

    public string TableCssClass
    {
        get;
        set;
    }

    public string EditAction
    {
        get;
        set;
    }
}

and I want to be able to send an instance of this object via parameters doing something like this:

, tableSettings => {
        tableSettings.TableCssClass = "table";
        tableSettings.EditAction = "action";
    });

CodePudding user response:

This lambda isn't creating an object.

Lambdas like these are used to configure already created objects, not create new instances. When you see code like this in a .NET Core example, the logging instance is created inside AddLogging itself :

services.AddLogging(logging => 
    {
        logging.SetMinimumLevel(LogLevel.Warning)
               .AddConsole();
    })

If you check the source code for AddLogging you'll see it creates a new LoggingBuilder instance and passes it as an argument to the lambda :

public static IServiceCollection AddLogging(this IServiceCollection services, 
        Action<ILoggingBuilder> configure)
{
   ...
   configure(new LoggingBuilder(services));
   return services;
}

CodePudding user response:

Why do you want to use a lambda to create an Object? You can just construct objects like in the following example.

, new ObjectName {
    Property1 = value1,
    Property2 = value2
});
  • Related