1) I’m still quite new to programming and have read a bit about getters and setters. But I really don’t understand why they are used.. Could anyone explain it, or point me to an article? (The ones I read were not really understandable for me…)
2) In my current project I have a class where I declare and initialize an array of structs. I now need to access the array from another class, but it gives me the error: An object reference is required to access non-static member 'BaseCharacter.Attributes'.
I figures this could mean I need to use getters and setters? But how does this work for arrays?
Thanks in advance!
Simon.
EDIT: 2nd question got solved, which brings me to something else. When I want to use some class in another one, I’m making a new instance of the class, right? And this means I get the original values?
But that’s not what I want.
The second class is used to generate the UI, and needs the values I’m keeping in the first class.
At some point I will implement save files (XML or even on a server in later stage). Can I then just get the values from those files?
For the getters and setters (the things that use them are called Properties) it’s just a convenient and nice-looking way to make people think they’re using a variable, but to do some computation whenever the variable is updated or accessed. For instance:
looks better than
Even though you can calculate the interest at the time it is requested in both cases.
They are also used to make a variable be able to be accessed from outside the class, but changeable only from within the class with this technique:
For an example of a setter being used, if you’ve ever used Windows Forms and updated a control’s
HeightorWidthproperty, you’re using a setter. While it looks like you’re using a normal instance variable likec.Height = 400, you’re really lettingcupdate it’s position by redrawing at a new place. So setters notify you exactly when a variable is changed, so your class can update other things base on the new value.Yet another application of Properties is that you can check the value people try to set the property to. For instance, if you want to maintain an interest rate for each bank account but you don’t want to allow negative numbers or numbers over 50, you just use a setter:
This way people can’t set public values to invalid values.
For your second question, you can do one of two things depending on what you’re trying to do.
One: You can make that member
static. That means that just one of them exists for the entire class instead of one per instance of the class. Then you can access it byClassName.MemberName.You can do that this way:
Two: You have to make an instance of the class and access the array through that. This means that each object will have its own seperate array.
You’d do that like this:
The second one is probably what you’ll want to do, since you probably will want to modify each character’s attributes seperately from all the other characters.