U
U
UZER20062013-08-09 15:14:40
C++ / C#
UZER2006, 2013-08-09 15:14:40

Question about getter and setter?

public class Editor
{
  public string Type
  {
    get;
    set {
      if (value == EditorType.Dictionary) Editable = false;
    }
  }
}

Can you please explain why this can't be done? What ideology does it violate? Why do I have to produce such a crutch construction in order to tritely change another property in the class when this is changed to a specific value?
public class Editor
{
  private string _type;
  public string Type
  {
    get { return _type; }
    set { _type = value;
      if (value == EditorType.Dictionary) Editable = false;
    }
  }
}

The search did not give an answer to the question, nor advice on how to properly implement such functionality.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
Illivion, 2013-08-10
@UZER2006

Your desired behavior violates the ideology of simplicity and transparency. For as soon as we allow such a construction, many questions arise with ambiguous answers. For example, "Which should be done first, the value assignment or the code in the setter?" or “What if an exception is thrown?” etc. The architects of the language correctly considered that the application developer should control the responses. Also, with this approach, some of the flexibility of the syntax is lost. So, it will no longer be possible to write value to one or another variable depending on the state of the object or assign a value to all elements of the internal collection.
You can use your second example, it will be correct and not at all crutch, but on the contrary, it will be very clear. You can also implement getter and setter methods, and this will also be correct and readable.

G
gouranga, 2013-08-09
@gouranga

C# has properties and auto-implemented properties (AIP) . Something intermediate is missing at the compiler level and is unlikely to appear in the future (in my opinion) . The question "why" can only be answered by the C# language and compiler architects at Microsoft. You can correctly implement such functionality only using the backing field, as you have in the second example.
If you really want to, you can use any AOP library (PostSharp, Fody, etc.) and implement this functionality, probably in a very crutch way. But why?
Richter is generally against these AIPs. :o)

L
LightSUN, 2013-08-09
@LightSUN

Is that so?

public class Editor
{
    public string Type
    {
        set
        {
            Editable = value != EditorType.Dictionary;
        }
    }
}

S
Sergey, 2014-10-13
@gasperoid

there is an opinion that you are using relative links when including css...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question