2

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}; } 
3
  • 1
    Of course you can do that, however you shouldn´t, or at least document it appropriately. Side-effects are a bad thing, basically. Properties are in fact nothing but usual get- and set-methods. You´re allowed to do everything you can do in a normal method as well. Commented Dec 11, 2017 at 12:23
  • 2
    Yes, you can. Did you try it? What happened? Read How to Ask. Commented Dec 11, 2017 at 12:23
  • gives syntax error. I know that it is not recommended or a good program styling (just was wondering if it is possible) Commented Dec 11, 2017 at 12:26

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

There is no need for => after the set you can use {..} instead. I think you are looking for a class like this:

class Sample { private int _Property; private int _ID; public int Property { get { return _Property; } } public int ID { get { return _ID; } set { _ID = value; _Property = value; } } } 

Here is an Example that shows the working,

Here the Property is a read only property you cannot set its value, it will automatically assigned when you set the value for ID

2 Comments

Nobody should be looking for a class like that. foo.Poperty = 1; foo.ID = 2; And now foo.Property is 2. Recipe for headaches.
@oerkelens: thanks for the point, Property should be readonly, I have updated the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.