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

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.
chenegarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

anarki_jimbelSenior DeveloperCommented:
First, a "property" is basically two distinct methods: one methods return what is stored in a private variable, and other method writes to this variable.

Of course, when you call "john.Name" you call the instance method. And really this executes "get" method to access underlying instance variable "private string name".
0
anarki_jimbelSenior DeveloperCommented:
Another question is "Why we use these getters and setters" instead of accessing directly "name" and "age" variables?  

Because sometimes you need to execute some additional code rather just return (or set) a variable. This is quite obvious with Age property. For a setter method it does not make sense to set "age" to a negative value or to a value greater. You can see this example for Age.

Same may have place for getters. Say, you have two variables: "name" and "surname". Now you want a public property FullName. getter will return:

            get { return (name + " " + surname; }

Open in new window

0
BeartlaoiCommented:
The get will be called any time you use john.Name in an expression so:
something = john.Name
Console.WriteLine("Name :{0}", john.Name);
These will both call get because they are retrieving Name, getting it.

set will be called any time you assign john.Name to something so:
john.Name = something;
will always call set because you are setting it.

You can put whatever code you want in the two functions that seems appropriate.
The main control on you is that a get MUST return a value.

So in a get you can just return the value from a local variable as done above.
You can also go further and do other things, like maybe retrieve the value from somewhere else and return it, or calculate a value to return, or even do some sort of work and return the result.  The point being is that you return a value.

In a set you could of course just put the new value into a local variable.
But you can do so much more, whatever you want to code it to do.  You can not only store the value but perhaps follow that with some computations, querying, filtering, reconnecting, etc.  Whatever work seems appropriate following changing that value you can do.  Sure, you can even ignore the incoming value entirely but that defeats the purpose of this method.

As for checking the value, in the example above the check is just determining if it is within a valid range before storing it.  This is a bad example as the proper way for dealing with a value out of range is to throw an exception explaining the issue, rather then just ignoring it without feedback.  Also this does not check for negative ages.
You can check the value not only to determine validity but to determine what to do like if age < 2 then treat like an infant, toddler, child, teen, tween adult, senior, whatever.
0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Mike EghtebasDatabase and Application DeveloperCommented:
chenegar,

For couple of years, I struggled with the concept of object oriented programming (oop). I have read over and over that is blue print and ... on an on. But why, why do we need blue print. Now, of course, I use concept daily and I appreciate its usefulness.

You most likely know most or all of the definitions about oop as most of us do. If you follow the story below, chances are you will be very comfortable with the concept of opp thus why we have get and set becomes supper easy. This is not from a grue to new-bee talk rather from new-bee to alike. After listening to grue to new-bee  talk, you have no choice to say yes, yes, of course because what they are saying is 100% correct but doesn't quite make sense.

Story:
In the past, speed of disk operation was too slow. The hardware technology was improving and so did software aspect of it. We know that the information is stored on a hard disk in zeros and ones. A text being was stored in scattered fashion all over the disk thus taking much longer to open that document because the disk head have to jump back and fort to locate all of the information and possibly put in the ram for user's use.

I am going replace a text file content with the information relating to a car. If we want to store the information about a car (possibly 10 data points, make, model, mileage, price, etc.) chances are these information will be scatted all over the hard disk.

But when you predict what kind of information a car may have, you in some fashion (I describe it shortly)  you reserve ample are such that all of the related information are kept all together.

How do we keep all related information together: We build a blue print of all the data points (properties) a car may need like:
Public Class Car
int Year
string model        (for now, I am not included get set until you feel the need for it.)

end class

Open in new window



When you write:

Car car1 = new Car();

avaiable car1 is created like                                this area is reserved to keep data for car1 at instantiation--v
                                                                                                                                        __________________________
car1  (at address d101 for example)                                        and at address d101 |                                                        car1 is at location 101                                                                                                  |
                                                                                                                                       |                                     |
                                                                                                                                       |                                     |
                                                                                                                                       |                                     |
                                                                                                                                        __________________________

Now, the data for car1 is not stored where varaible car1 is.
car1 is know as reference type variable. it uses address recorded near d101 to locate the actual area at d101 (above)
to work with its information.

Now what. Ok, we have car1 and we want to use it.

I want you tell me how can use concept like get and set to store the information for this car or read them back when we need them.

I meant to do this part myself but I have to something else now.

Please not that my explanation is simplistic and put together in this manner to explain illustrate it without use of technical vocabulary.  


Please describe to me how we can use get and set to communicate with car1 object. car1 is object because it exist. The calss Car is not an object it is just a template (class, blueprint).
Regards,

Mike
0
anarki_jimbelSenior DeveloperCommented:
Just to add on code explanation:
Person john = new Person("John Doe", 24);

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

Open in new window


OK, first line is a constructor call. Of course, in the real life it's a bit different, I'd suggest a bit different constructor, something like
 new Person(mom, dad);

Open in new window

:). However, in a programming task we want to have a person with age 24 right now and do not care about parents :). Therefore we choose constructor we want.

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?

First, Person is a constructor, not a method. I.e it is a method but very special one: it is called to create an object, just once. It takes values you provide and writes them into name and age variables (into memory these variables point to!). Second, method does not hold any data, it cannot. . Data is hold in some memory, and a variable name POINTS to this location. So, when we call "john.Name" the we go to Name--> get method, and this method returns a variable "name", or, if you want, a content of memory the variable points to (it happens without our involvement, thanks computer engineers and language developers :))., .
0
chenegarAuthor Commented:
None of you have really answered my question yet. What does "get" get?

anarki jimbel, I think you've come the closest to helping me sort this out. You said:

First, a "property" is basically two distinct methods: one methods return what is stored in a private variable, and other method writes to this variable.

I think this means that Get returns the value of a private variable and Set writes to the private variable. But I still don't know what "get" gets. Does it get the value of the private variable to return?
0
käµfm³d 👽Commented:
What anarki_jimbel stated is accurate. The compiler does a bit of magic for you whenever you create a get/set. It turns these into standard get_Blah() and set_Blah() methods (like you do in Java). You never see this because the compiler does the work. Your code simply shows the get and set. So what really happens to the code you've written above is that the compiler creates something similar to:

    public string get_Name()
    {
        return name;    
    }
    
    public void set_Name(string value)
    {
        name = value;
    }

    public byte get_Age()
    {
        return age;    
    }
    
    public void set_Age(byte value)
    {
        name = age;
    }

Open in new window


As you can see, each method refers to a private member field (variable).
0
chenegarAuthor Commented:
So another class calls the get_Name() method, which returns the value of the private variable name? And the get_Age method is called by another class and returns the value of the private variable age?

Does this mean that the answer to my question is that the get accessor "gets" the value of a private variable that is passed in through a constructor or method then returns it to the calling class?

I don't mean to be so thick about this, but I am really struggling with how to make this make sense to me.
0
käµfm³d 👽Commented:
So another class calls the get_Name() method, which returns the value of the private variable name?
Yes.

And the get_Age method is called by another class and returns the value of the private variable age?
Yes.

Does this mean that the answer to my question is that the get accessor "gets" the value of a private variable...
Yes.

...that is passed in through a constructor or method then returns it to the calling class?
Kind of. It may be passed via a constructor or a method, but it could have been set by anything. The value that is "set" for the member variable doesn't have to be set by an external class. If I added another method to your class:

e.g.

public void DoSomething()
{
    // blah blah

    if (DateTime.Today = DateTime.Parse("04/01/2014"))
    {
        this.name = "April Fools!";
    }
}

Open in new window


The value that gets put into name did not come from the outside...though a method did set the value.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
chenegarAuthor Commented:
So
public string get_Name()
    {
        return name;    
    }

Open in new window

returns "April Fools!" to whatever called it?
0
käµfm³d 👽Commented:
If DoSomething() was called at some point prior, yes.
0
chenegarAuthor Commented:
I think I've got it. Thank you for patiently answering my questions.
0
käµfm³d 👽Commented:
You might consider sharing the love with anarki_jimbel. He really said the same thing; I just expanded on it  = )

Just keep in mind that get/set are pretty much shorthand ways of writing get_XXXX/set_XXXX.

To really blow your mind, C# also has auto-implemented properties. Such properties are another compiler trick. Basically, with auto-implemented properties you no longer have to have a backing variable--you still have one, but the compiler creates it and you never see it. An auto-implemented property looks like this:

public SomeType SomePropertyName { get; set; }

Open in new window


You'll notice that the get and set don't have bodies. That's because the compiler generates the logic to return the value from the backing variable that it itself created.

I only mention auto-implemented properties so that you'll be aware of what they are should you ever see them in the wild.
0
anarki_jimbelSenior DeveloperCommented:
Thanks Kaufmed :). I don't much care about points but it's nice when people appreciate someone's efforts :).
0
chenegarAuthor Commented:
You're right, I should share the love with anarki_jimbel. Do you know how I change the points?
0
chenegarAuthor Commented:
And, thanks for describing auto-implemented properties. I understood them as shorthand for the private (backing) variables. It's easier to work with the auto-implemented properties now that I have an understanding of how get and set work.
0
käµfm³d 👽Commented:
Do you know how I change the points?
Click "Request Attention" just below the original question.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.