Change multiple properties of an object in one command

  • A+
Category:Languages

Here is an object with three properties:

public class myClass {    public int score { get; set; }    public string name { get; set; }    public bool isAlive { get; set; } } 

after creating an instance of this class, in some places, I'm changing two or three properties of this instance like this:

targetInstance.score = 1; targetInstance.name = "John"; targetInstance.isAlive = true; 

is there any way to use targetInstance once and then in a way using some brackets just sets the properties (like initialization), something similar to this:

targetInstance = { score = 1, name = "John" } 

Note: maybe you suggest to have a method which takes these and change the properties, but it is not suitable while there are so many properties.

 


Named parameters

You could write a method with named, default parameters, and use named arguments to update only the ones you want.

For example:

public class myClass {    public int score { get; set; }    public string name { get; set; }    public bool isAlive { get; set; }     public void Set(int score = -1, string name = null, bool? isAlive = null)    {        if (score != -1) this.score = score;        if (name != null) this.name = name;        if (isAlive.HasValue) this.isAlive = isAlive.Value;    } } 

You can call it like this:

var o = new myClass(); o.Set(name: "Hello"); 

Or

var o = new myClass(); o.Set(name: "Hello", isValid: false); 

Or

var o = new myClass(); o.Set(score: 100, isValid: false); 

Fluent syntax

You can create a set of "setter methods" that are chainable, like so:

public class myClass {    public int score { get; set; }    public string name { get; set; }    public bool isAlive { get; set; }     public myClass SetScore(int score)    {        this.score = score;        return this;    }     public myClass SetName(string name)    {        this.name = name;        return this;    }     public myClass SetIsAlive(bool isAlive)    {        this.isAlive = isAlive;        return this;    } } 

Then use it like this:

var o = new myClass(); o.SetName("Donald").SetIsAlive(true); 

Or like this:

var o = new myClass()     .SetName("Bob")     .SetScore(0)     .SetIsAlive(true); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: