Wow ok so I just found this thread and am eager to ask some questions!
First off, I am learning C# as my first language: is this a good idea? I am already about half way through a ‘Learn C# in 21 Days’ book and, although people were telling me to look at Java, I figured I should plow on with what I have and hopefully it will be easy to transition anyway if it makes sense in a career context (something I am, in the long term, aiming for).
Sooo… ok where to start. Well, I’d like to test out if I understand something correctly or not and that is the ‘get’ and ‘set’ keywords in C#.
The example in the book is for setting up ‘properties’ for private variables. This means that you set up a public variable that other classes can access (such as your Main class), and then use this public variable to set the private variable. Apparently it makes sense to keep some variables private and, although I don’t fully understand why at the moment, I guess I can sort of guess at it (code which is constantly referring to the same variable might end up being slower/more buggy in unpredictable ways due to storage issues?)
So ok here’s how I see it at the moment:
private int x;
public int y
x = value;
y = 5;
Now, here’s how I’m understanding this at the moment:
- when you make the literal ‘5’, and have it ready to put into the public integer ‘y’, the ‘get’ block of code executes (which ‘returns’ the private variable ‘x’)
- when you actually put the ‘5’ into ‘y’, the ‘set’ block of code executes (putting the ‘value’ of y into x)
So, in a way, what get and set do is deconstruct the process of actually allocating values to variables in order to squeeze in a couple of other processes (properties)?
So hey I hope this thread will keep my motivation up for this. I’ve just read about protected variables at the moment, which are basically like private ones but are accessible to derived classes.
Ah ok so one other question… in what other ways are ‘get’ and ‘set’ used other than for manipulating private variables as above?