In javascript, you're able to pass a dynamic object and have its values assigned to an object. Overriding the current values, but only on the members that are specified.
For Example:
class Options
{
constructor()
{
this.foo = 123;
this.fee = false;
this.nothing = 1.23;
this.thing = new MouseEvent();
}
}
var globalOps = Options();
void doTest(ops = null)
{
var currentOps = Object.assign({}, globalOps); // clone it to not override the global options
// Copy over the new members specified
if(ops != null)
Object.assign(currentOps, ops);
console.log(currentOps.foo); // outputs 555 - default was 123
console.log(currentOps.fee); // outputs true - default was false
console.log(currentOps.nothing); // outputs 1.23 - default was 1.23
console.log(currentOps.thing); // outputs null - default was instance of MouseEvent()
}
globalOps.fee = true;
doTest({
foo: 555,
thing: null
});
I want to know if its possible to do the same thing in C#.
Things I've tried:
- Made every member nullable and checked if
HasValue
is set to true to copy over the values
Not an ideal solution since I'm using .NET Framework and by default it doesn't support nullable reference types
. Requires some hacky packages to add support for that.
- Passed a dynamically created object and used
JsonConvert.Populate()
to copy over the values
Not an ideal solution since the dynamic object doesn't contain any definitions so no intellisense. I'd have to know exactly what every member type is.
- Create a shallow clone of the object. Then assign the values I want and pass that clone as the parameter.
Not an ideal solution since its not intuitive to anyone that reads the code that they should clone the main config instance and use that instead of passing a new instance.
- Put all the members as optional parameters in the function prototype
Not an ideal solution since it doesn't support nullable reference types
and requires specifying every member.
How can I ideally pass an object with only certain members set as the overrides and the rest use the default instance's values?