Answer the question
In order to leave comments, you need to log in
Question about getter and setter?
public class Editor
{
public string Type
{
get;
set {
if (value == EditorType.Dictionary) Editable = false;
}
}
}
public class Editor
{
private string _type;
public string Type
{
get { return _type; }
set { _type = value;
if (value == EditorType.Dictionary) Editable = false;
}
}
}
Answer the question
In order to leave comments, you need to log in
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.
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)
Is that so?
public class Editor
{
public string Type
{
set
{
Editable = value != EditorType.Dictionary;
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question