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.

Thanks

Recommended Answers

All 2 Replies

It is just shortcut syntax for:

 private string XRandom;            

        public string random
        {
            get
            { return random; }
            set 
            { 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.