Is it possible to set multiple values in a set method?
I want to do something like the following:
public int ID { get; set => {Property = value, ID=value}; }
Expression-bodied setters don't have the expressive power to do more than one operation, so you need to use the full method body syntax:
private Foo foo;
public Foo Foo
{
get { return foo; }
set
{
foo = value;
OtherProperty = value.SomethingElse;
}
}
It's reasonable to do this in some cases, because some operations have side effects by their very nature. For example, if you're setting an object's time zone property, it makes sense to alter the underlying DateTime
to ensure that its DateTimeKind
is DateTimeKind.Local
. If you don't, the object's DateTime
property is incomplete or wrong.
That said, if you find yourself doing this everywhere, you may want to rethink your design, because overuse is a code smell.