Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

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

Posted on 2014-08-13
18
Medium Priority
?
228 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.
0
Comment
Question by:chenegar
  • 6
  • 5
  • 4
  • +2
17 Comments
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40259514
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
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40259529
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
 
LVL 9

Expert Comment

by:Beartlaoi
ID: 40259531
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 34

Expert Comment

by:Mike Eghtebas
ID: 40259664
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
 
LVL 30

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 800 total points
ID: 40259669
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
 

Author Comment

by:chenegar
ID: 40260714
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40260750
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
 

Author Comment

by:chenegar
ID: 40260998
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
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 1200 total points
ID: 40261050
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
 

Author Comment

by:chenegar
ID: 40261168
So
public string get_Name()
    {
        return name;    
    }

Open in new window

returns "April Fools!" to whatever called it?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40261181
If DoSomething() was called at some point prior, yes.
0
 

Author Comment

by:chenegar
ID: 40261226
I think I've got it. Thank you for patiently answering my questions.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40261314
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
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40261706
Thanks Kaufmed :). I don't much care about points but it's nice when people appreciate someone's efforts :).
0
 

Author Comment

by:chenegar
ID: 40263095
You're right, I should share the love with anarki_jimbel. Do you know how I change the points?
0
 

Author Comment

by:chenegar
ID: 40263103
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40263114
Do you know how I change the points?
Click "Request Attention" just below the original question.
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Enter Foreign and Special Characters Enter characters you can't find on a keyboard using its ASCII code ... and learn how to make a handy reference for yourself using Excel ~ Use these codes in any Windows application! ... whether it is a Micr…

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question