Hey guys,

I don't really understand the usage of the get/Set/return keywords.

get-Read Only
set-Write Only(eh)
return-Returns value to calling method

Those are the definitions I have but can I have a small explanation on when to use these and how to use the get/set thank you very much.

3 Years
Discussion Span
Last Post by LetGoFool

get and set are used with properties. return is used with methods that want to pass a value back to the calling code.

public int Age {get; set;} // Automatic property, don't have to worry
                           // about where it stores the value

private int weight;

public int Weight {                      // Normal property, we have to write the code
    get {                                // and have a place to store it. This lets us
        return weight;                   // do things like add validation to make sure
    }                                    // the value is in range, etc.
    set {
        if (value > 0) weight = value;   // 'value' is the automatic name of the value
    }                                    // assigned.

public int MultiplyByTwo(int x) {
    return x * 2;   // the return tells it what value we want to pass back to the
}                   // calling method. The type must match the type given before
                    // the method name, in this case, an int

public void UseStuff() {
    Weight = 43;                         // Assigning to the property automatically
                                         // calls the 'set' method of the property.
    int result = MultiplyByTwo(Weight);  // Here we are calling the method defined
}                                        // above and passing it the value of the 
                                         // Weight property (get is automatically
                                         // called here). The value returned is assigned
                                         // to the result variable.

Edited by Momerath

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.