Mathieu
Mathieu

Reputation: 4520

Avoiding redundancy in updating an object's properties

When I instantiate a new entity, it looks like this:

var myEntity = new MyEntity() 
{
    Field1 = "myValue",
    Field2 = "myOtherValue",
    ...
}

This avoids having to write myEntity.Field1 many time.

But when I have to update multiple properties, I don't know any way to avoid the repetition of code. So at the moment, I do like this:

myEntity.Field1 = "myNewValue";
myEntity.Field2 = "myOtherNewValue";
...

Does C# allow any more concise way of updating multiple properties?

Upvotes: 1

Views: 1979

Answers (3)

Eric Andres
Eric Andres

Reputation: 3417

Going on @daryal's comment above, you could create an update method with all of the parameters being optional:

public void UpdateEntity(string Field1 = null, string Field2 = null, string Field3 = null) 
{
  this.Field1 = Field1 ?? this.Field1;
  this.Field2 = Field2 ?? this.Field2;
  this.Field3 = Field3 ?? this.Field3;
}

Then call it with named parameters:

e.UpdateEntity(Field1: "foo", Field3: "fiz");

It's not the cleanest solution, but another option. If I were doing stuff like this all of the time, I would probably go with the "C# with keyword equivalent" that @Brian shared.

Note: this solution requires C# 4.

Upvotes: 2

Brian
Brian

Reputation: 1823

Check out the C# with keyword equivalent. It's a bit sloppy, but it is the closest you can get to the VB.NET With statement.

Also take a look at this blog post: Simple equivalent of “With” statement in C#

Upvotes: 6

Mark Brackett
Mark Brackett

Reputation: 85655

Nope. VB.NET has the With statement, but there's no equivalent in C#.

Upvotes: 1

Related Questions