We help IT Professionals succeed at work.
Get Started

How can I understand C#'s get; and set; properties conceptually?

chenegar
chenegar asked
on
265 Views
Last Modified: 2014-08-21
I'm teaching myself C# and I've run into a conceptual problem with getters and setters. I know that you use them to encapsulate variables, keeping them private within a class and using them outside of the class. They prevent unwanted changes by methods outside of the class. What I don't understand -- conceptually -- is what they're doing.

For example, the Person class is defined as follows:
class Person
    {
        private string name;
        private byte age;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        
        public byte Age
        {
            get { return age; }
            set 
            {
                if (value <= 130)
                {
                    age = value;
                }
            }
        }
                
        public Person(string personName, byte personAge)
        {
            name = personName;
            age = personAge;
        }
    }

Open in new window


Then the properties are called with this code in the Program class:
Person john = new Person("John Doe", 24);

Console.WriteLine("Name :{0}", john.Name);

Open in new window


How can I describe this in English? Everything I've come across uses code and it doesn't make it any clearer to me. When the code in the Program class calls the Name property, does Name get the name (John Doe) from the john instance? Or is it getting it from the Person method?

I know set can be used to test a value, as the property Age does. Does set then give the value back to get to return to the Program class?

I stumble over get and set every time I try to read through code, so I'd greatly appreciate whatever you experts can do to help me sort this out.
Comment
Watch Question
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This problem has been solved!
Unlock 2 Answers and 17 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE