I understand the concept of using get and set with instance variables, but I am confused about using get and set by themselves
For example

public string random {get; set;}

what is the purpose of this, and how can I use this in my code. I am a beginning programmer any help would be great help.


It is just shortcut syntax for:

 private string XRandom;            

        public string random
            { return random; }
            { random = value; }

The compiler comes up with his own private field, so you don't have to bother.
It is just a 'lazy programmers' thing. Think of it if you were to write a class with 100 properties, what syntax would you prefer?

The get and set allow you to use code to adapt the input to fit the property. For instance if the values allowed for the property are restrictive you can validate the input in the set before passing the value to the property. Another use of these is to obscure the property itself. By keeping it private and allowing the user to only access it through a public property, your internal code can use the property directly but that property and how it's used isn't exposed to the user. In general though unless you have an overriding need the defaults will work fine.

This article has been dead for over six months. Start a new discussion instead.