0

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?

John
  • 5,942
  • 3
  • 42
  • 79
  • https://stackoverflow.com/questions/391483/what-is-the-difference-between-an-abstract-method-and-a-virtual-method - though another part of your question is probably how to deserialize JSON to the correct derived type. – ProgrammingLlama Jul 20 '22 at 01:46
  • @DiplomacyNotWar instead of json, I would probably just use refactoring or a object cloning library rather than serializing and then deserializing with json in order to copy/map all the members since it would be faster and not have any data loss. But using a dynamic object doesn't contain a set class definition so I don't have intellisense to tell me all the members. Thats why I'm not using that solution. – John Jul 20 '22 at 01:56

0 Answers0