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
Func<T>and have something like() => new Customer { Name: "zzz", Info: "Abc" }?Name: "Zzz",here you are hardcoding the value. maybe your real use case is using values from somewhere else?Actioncould 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. So no, what you want isn't possible.