I want to write a method that has optional parameters. It should update some object with only those parameters that were given to it while leaving other properties unchanged.
The problematic part:
- Null is a valid value for all object properties
- The value of object properties can not be read to compare with
What should the signature of the method be and what should the logic of the method be?
So lets say the object looks like this:
public class Foo
{
public int Id { get; set; }
public bool? MyBool { get; set; }
public int? MyInt { get; set; }
public string MyString { get; set; }
}
And lets say the method looks like this:
public void UpdateObject(int id, bool? optBool = null, int? optInt = null,
string optString = null)
{
var objectToUpdate = _fooList.FirstOrDefault(x => x.Id = id);
if(objectToUpdate != null)
{
// Update only set properties?
}
}
Now, I want to call that method to update properties in different parts of my application like this:
// at some part of app
UpdateObject(1, optInt: 5);
// will set the int property to 5 and leaves other properties unchanged
// at other part of app
UpdateObject(1, optString: "lorem ipsum");
// will set the string property and leaves other properties unchanged
// at other part of app
UpdateObject(1, optBool: null, optString: "lorem ipsum");
// will set the string and bool property and leaves other properties unchanged
Please note that just setting values will not work because it will overwrite unwanted properties with null.
public void UpdateObject(int id, bool? optBool = null, int? optInt = null,
string optString = null)
{
var objectToUpdate = _fooList.FirstOrDefault(x => x.Id = id);
if(objectToUpdate != null)
{
// This is wrong
objectToUpdate.MyBool = optBool;
objectToUpdate.MyInt = optInt;
objectToUpdate.MyString = optString;
}
}