Home > Net >  C# method syntax similar to object initializer
C# method syntax similar to object initializer

Time:01-27

We have an extension method that accepts an action to initialize an object. Is there some way to improve the syntax of such a call:

public static T NewRow<T>(this IUow uow, Action<T> action();

// this does internally call
public T NewRow<T>(Action<T> initializer) where T : IBo
{
    T bo = NewRow<T>();
    initializer.Invoke(bo);
    return bo;
}

uow.NewRow<ICustomer>(customer => { 
        customer.Name = "Zzz";
        customer.Info = "Abc"
);

I thought maybe I could use something similar to the object initializer syntax?

uow.NewRow<ICustomer>({ 
      Name: "Zzz",
      Info: "Abc"
});

The idea is to get rid of customer.* = ... in every line.

I would be happy for any tip.

INFO:

  • We are using the latest C# language version
  • The solution should support IntelliSense (e.g., Name and Info should be proposed to the user)

Edit:

  • I can't use a constructor because I only have an interface. No class/implementation. The framework behind creates the object to the given interface T bo = NewRow<T>();. Which actual object gets created is decided by the framework
  • Also initializers like { Name: myOtherVariable.FirstName } should be possible

CodePudding user response:

an Action could be everything, not just a simple assignment. So if a client chosed to make a function-call instead, there literally is nothing to shortcut here. See this for example:

uow.NewRow<IWhatever>(() => Console.WriteLine("tataaaa"););

So no, what you want isn't possible.

However you could create some kind of EventsArgs that hold your names and use those within your NewRow-method. There's no need for an action if all those callbacks should actually be just assignement-calls alltogether.

uow.NewRow<ICustomer>(new MyArgs { 
    Name = "Zzz",
    Info = "Abc"
});

And within NewRow:

public T NewRow<T>(MyArgs args) where T : IBo 
{
    customer.Name = args.Name;
    customer.Info = args.Info;
}
  •  Tags:  
  • Related