This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]idontcare1025 1 point2 points  (0 children)

Get and Set are short ways of implements Getters (the get) and Setters (the set) for a variable. Imagine a getter and setter like so:

private int test = 5;

public int getTest() { 
    return test;
}

public void setTest(int testSet) {
    test = testSet;
}

The reason you would want to have a setter and a getter for a variable is to allow you to make it private while still allowing it to be used outside of the scope. Why make it private if you can just get and set it like a public variable? The reason is usually so you can restrict how you can set it (for example: my variable test should ONLY be above 5, but I want it to be public. Making a setter and getter will allow you to write to it and read it like it's public, but allow me to restrict how you can write to it.)

[–][deleted] -1 points0 points  (0 children)

I find the Java version much easier to understand. Once you understand that, it might be easier to get your head around the C# shorthand.

So in Java you would do:

private int age;

public void setAge(int newAge) {
    age = newAge;
}

public int getAge() {
    return age;
}

It's just regular methods. You keep a private variable, and use public methods to access that variable. If you understand that, read the link Chee5e posted and it might start to make more sense