I’m currently working on a project where I need to make specific changes to an existing object without touching the non-changing properties. I started going down a road that I kindof liked, but ended up having to change gears. I have a feeling I’ll come back to this class sometime later on. Also, I’d LOVE to hear some feedback on this class from the community. For those reasons, I’m posting it here:
public interface IObjectPropertyChangerActor<out T>
{
IObjectPropertyChangerActor<T> With(Action<T> action);
IObjectPropertyChangerActor<T> And(Action<T> action);
}
public class ObjectPropertyChangerActor<T> : IObjectPropertyChangerActor<T>
{
readonly T _objectToChange;
public ObjectPropertyChangerActor(T objectToChange)
{
_objectToChange = objectToChange;
}
#region IObjectPropertyChangerActor<T> Members
public IObjectPropertyChangerActor<T> With(Action<T> action)
{
return MakeTheChange(action);
}
public IObjectPropertyChangerActor<T> And(Action<T> action)
{
return MakeTheChange(action);
}
#endregion
IObjectPropertyChangerActor<T> MakeTheChange(Action<T> action)
{
action.Invoke(_objectToChange);
return this;
}
}
public static class ObjectChangingExtensions
{
public static IObjectPropertyChangerActor<T> Change<T>(this T objectToChange)
{
return new ObjectPropertyChangerActor<T>(objectToChange);
}
}
Then, you use it like this:
public class Car
{
public string Color { get; set; }
public string Model { get; set; }
public string Make { get; set; }
public string Year { get; set; }
}
public class given_an_object_property_changer_context
{
[Test]
public void it_should_change_the_object_properties_as_expected()
{
var myCar = new Car
{
Color = "Blue",
Make = "Chevy",
Model = "Cruze",
Year = "2011",
};
myCar.Change()
.With(x => x.Color = "Red")
.And(x => x.Year = "2012");
ExpectThatTheChangesWereMade(myCar);
}
void ExpectThatTheChangesWereMade(Car myCar)
{
Assert.AreEqual(myCar.Color, "Red");
Assert.AreEqual(myCar.Year, "2012");
}
}
I’m still considering this thing’s usefulness. My current problem is creating the list of changes from a complex object. Useful or not, I enjoyed my stroll through nerd-land (and it gave me an excuse to put my car on my blog).