Answer the question
In order to leave comments, you need to log in
Why are access methods needed?
I'm learning C#, stumbled upon them and don't really understand why they are needed. MSDN gives only examples of use and so the captain's things.
Why get and set?
What's the difference between
protected int size = 3;
public int GetSize1()
{
return size;
}
and
public int GetSize2()
{
get
{
return size;
}
}
?
Answer the question
In order to leave comments, you need to log in
In Java, it is customary to write getters and setters for variables, and make the variables themselves private.
Reasons 3:
1) After the code is written and has worked for a couple of years, it will be easy to add functionality to a getter or setter without changing the code that uses them.
2) Encapsulation. For example, this way you can allow reading the value variable, but prohibit changing it.
3) The JavaBeans convention requires this + there is a standard for getter and setter names.
C# is a clone of Java, so the first 2 reasons also apply here.
But Microsoft always complicates things, so properties were added to the language.
They are the same getters / setters, only with eye-catching syntax and a bunch of new keywords.
@PokimonFromGamedev you are not quite right.
Yes, the first two reasons really work that way. But in the first case, we declare just a method, but in the second case, a property.
It doesn't really matter until you need to bind the data, and that's where the difference becomes important.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question