1

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}; }
rianjs
  • 7,767
  • 5
  • 24
  • 40
Wouter
  • 1,293
  • 2
  • 16
  • 34
  • 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. – MakePeaceGreatAgain Dec 11 '17 at 12:23
  • 2
    Yes, you can. Did you try it? What happened? Read [ask]. – CodeCaster Dec 11 '17 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) – Wouter Dec 11 '17 at 12:26

2 Answers2

4

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.

rianjs
  • 7,767
  • 5
  • 24
  • 40
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

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88