Search code examples
c#lambdafunc

How to update object properties with Func<>?


Is it somehow possible to update object properties by using Func with lambda expression?


Foo class

public class Foo
{
    public int Id      { get; set; }
    public string Name { get; set; }
    public int Age     { get; set; }
    //... many others
}

Util class

public static class Updater
{
    public Foo FooUpdate(Foo item, params Func<Foo, object> properties)
    {
        foreach(var property in properties)
        {
            //take value of property and set it on item object
        }
        return item
    } 
}

Initial call

   var updatedFoo = Updater.FooUpdate(item, p => p.Id = 10, p => p.Name = "Test", ...);

After FooUpdate method, I want to receive updatedFoo object, with given value parameters in given call. Id = 10 and Name = "Test".


Solution

  • The Func<Foo, object> signature is invalid. A lambda p => p.Id = 10 does not return an object. If you wanted to simply change the existing method to work then this would do:

     public Foo FooUpdate(Foo item, params Action<Foo> properties)
     {
         foreach(var property in properties)
         {
            property(item);
         }
         return item
     } 
    

    But please note that this is a pretty bad design. First of all, your method both modifies the passed item and returns it - it should either modify it (and return void) or leave item as it was, clone it and then modify and return the clone. Second of all, I see no value at all in this Util method. Any call to it would be equivalent to just applying the updates line by line.

    var updatedFoo = Updater.FooUpdate(item, p => p.Id = 10, p => p.Name = "Test", ...);
    

    is the same as

    item.Id = 10;
    item.Name = "Test";
    /* ... */