Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. What's the purpose to use Property with set and get to change a field?

What's the purpose to use Property with set and get to change a field?

Scheduled Pinned Locked Moved C#
questioncsharp
17 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    nstk
    wrote on last edited by
    #1

    As I know from OOP theory, the purpose of private Properties is to have the variables of an object protected from other classes, that could accidentaly change their value, thus provoking complications in a software. Am I correct till here? Then I started to read C# and I found out that variables are called fields and they are also usually private. But there are also Properties with set and get which are used to change variables' (fields') values. For instance: I have a variable category in a class Myclass. To follow strict C# grammar I write private int cat; and then I create a property with set and get public int Category { get { return cat; } set { cat = value; } } Therefore I can access the property from any other class using Myobject.Category = 5 And here comes the question: why use such a complicated way? Why not use directly a public cat field? After all, cat is still not protected since I can directly change Category instead. Thanks in advance for any reply.

    J H P J 4 Replies Last reply
    0
    • N nstk

      As I know from OOP theory, the purpose of private Properties is to have the variables of an object protected from other classes, that could accidentaly change their value, thus provoking complications in a software. Am I correct till here? Then I started to read C# and I found out that variables are called fields and they are also usually private. But there are also Properties with set and get which are used to change variables' (fields') values. For instance: I have a variable category in a class Myclass. To follow strict C# grammar I write private int cat; and then I create a property with set and get public int Category { get { return cat; } set { cat = value; } } Therefore I can access the property from any other class using Myobject.Category = 5 And here comes the question: why use such a complicated way? Why not use directly a public cat field? After all, cat is still not protected since I can directly change Category instead. Thanks in advance for any reply.

      J Offline
      J Offline
      JF2015
      wrote on last edited by
      #2

      Hi, see these links for some explanation: http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx[^] http://msdn.microsoft.com/en-us/library/w86s7x04%28VS.80%29.aspx[^] Hope it helped!

      N 1 Reply Last reply
      0
      • J JF2015

        Hi, see these links for some explanation: http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx[^] http://msdn.microsoft.com/en-us/library/w86s7x04%28VS.80%29.aspx[^] Hope it helped!

        N Offline
        N Offline
        nstk
        wrote on last edited by
        #3

        Thanks for the links. Still, it confuses me a bit, in the way that I have to give two different names in order to describe one object variable. like in the example above. The word 'Category' has a meaning for my class, but I am obliged to use a different word for the field, therefore I chose cat, but I find it poor in a semantic way. Also, I am wondering if that is a Microsoft's "invention" or a general OOP thinking. Does it exist in Java too? I never met it in C++, MFC or other frameworks, nor in UML.

        J 1 Reply Last reply
        0
        • N nstk

          As I know from OOP theory, the purpose of private Properties is to have the variables of an object protected from other classes, that could accidentaly change their value, thus provoking complications in a software. Am I correct till here? Then I started to read C# and I found out that variables are called fields and they are also usually private. But there are also Properties with set and get which are used to change variables' (fields') values. For instance: I have a variable category in a class Myclass. To follow strict C# grammar I write private int cat; and then I create a property with set and get public int Category { get { return cat; } set { cat = value; } } Therefore I can access the property from any other class using Myobject.Category = 5 And here comes the question: why use such a complicated way? Why not use directly a public cat field? After all, cat is still not protected since I can directly change Category instead. Thanks in advance for any reply.

          H Offline
          H Offline
          Hiren solanki
          wrote on last edited by
          #4

          Let me give you the strong need of property in C#. Suppose there's one field CustomerID and you have assigned CustomerIDProperty to get and set values for CustomerID. Now After a years requirements being changed and They say they need some validation on CustomerID now you can not change or not advisable to put a check of CustomerID everywhere in the code, At that time you can simply put check at set method of CustomerIDProperty to be rescued. Property is introduced because of the changing requirement in software field. "Walking on water and devloping a software both are the easy things,Provided both FROZEN".

          Regards, Hiren.

          My Recent Article: - Way to know which control have raised PostBack
          My Recent Tip/Trick: - Remove HTML Tag, get plain Text

          J 1 Reply Last reply
          0
          • N nstk

            As I know from OOP theory, the purpose of private Properties is to have the variables of an object protected from other classes, that could accidentaly change their value, thus provoking complications in a software. Am I correct till here? Then I started to read C# and I found out that variables are called fields and they are also usually private. But there are also Properties with set and get which are used to change variables' (fields') values. For instance: I have a variable category in a class Myclass. To follow strict C# grammar I write private int cat; and then I create a property with set and get public int Category { get { return cat; } set { cat = value; } } Therefore I can access the property from any other class using Myobject.Category = 5 And here comes the question: why use such a complicated way? Why not use directly a public cat field? After all, cat is still not protected since I can directly change Category instead. Thanks in advance for any reply.

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #5

            Because you can then provide validation code. But if you don't want to, then try an automatically-implemented property instead.

            1 Reply Last reply
            0
            • N nstk

              As I know from OOP theory, the purpose of private Properties is to have the variables of an object protected from other classes, that could accidentaly change their value, thus provoking complications in a software. Am I correct till here? Then I started to read C# and I found out that variables are called fields and they are also usually private. But there are also Properties with set and get which are used to change variables' (fields') values. For instance: I have a variable category in a class Myclass. To follow strict C# grammar I write private int cat; and then I create a property with set and get public int Category { get { return cat; } set { cat = value; } } Therefore I can access the property from any other class using Myobject.Category = 5 And here comes the question: why use such a complicated way? Why not use directly a public cat field? After all, cat is still not protected since I can directly change Category instead. Thanks in advance for any reply.

              J Offline
              J Offline
              Jeff Connelly
              wrote on last edited by
              #6

              nstk wrote:

              As I know from OOP theory, the purpose of private Properties is to have the variables of an object protected from other classes, that could accidentaly change their value, thus provoking complications in a software. Am I correct till here?

              Only partially. The other reason is to hide the implementation, so that it can change in the future. The calling code only needs to know the property name (or private function name). However you can change how you calculate the value. So it's for future change, as well as current privacy. That's where the complication of properties comes in handy. Next month, you might rewrite your Category property to look like this public int Category { get { if (cat < 0) return 0; else return cat; } set { cat = value; } }

              1 Reply Last reply
              0
              • N nstk

                Thanks for the links. Still, it confuses me a bit, in the way that I have to give two different names in order to describe one object variable. like in the example above. The word 'Category' has a meaning for my class, but I am obliged to use a different word for the field, therefore I chose cat, but I find it poor in a semantic way. Also, I am wondering if that is a Microsoft's "invention" or a general OOP thinking. Does it exist in Java too? I never met it in C++, MFC or other frameworks, nor in UML.

                J Offline
                J Offline
                Jeff Connelly
                wrote on last edited by
                #7

                nstk wrote:

                The word 'Category' has a meaning for my class, but I am obliged to use a different word for the field, therefore I chose cat, but I find it poor in a semantic way.

                Typically you will use Category for the property name and category or _category for the local variable name. The same OO concept existed in C++ - it was simply a public method though. Properties are not necessary, it's just a new way of saying "public method that returns a value and keeps the value private." In C++ you'd simply write a public function, and some people even used the word "Get". public int GetCategory() { return category; } public void SetCategory(int i) { category = i; } Same thing. However C# property offers you a convenient way of not even declaring the local variable! For example this works without even declaring your local variable called "cat". public int Category { get; set; } Again, this is for future use, where you have the option of changing how Category gets implemented (you can add a variable later, or write the get or set methods with some different code, but the caller would never need to know.) In the mean time, the compiler generates a local variable under the covers for you.

                1 Reply Last reply
                0
                • H Hiren solanki

                  Let me give you the strong need of property in C#. Suppose there's one field CustomerID and you have assigned CustomerIDProperty to get and set values for CustomerID. Now After a years requirements being changed and They say they need some validation on CustomerID now you can not change or not advisable to put a check of CustomerID everywhere in the code, At that time you can simply put check at set method of CustomerIDProperty to be rescued. Property is introduced because of the changing requirement in software field. "Walking on water and devloping a software both are the easy things,Provided both FROZEN".

                  Regards, Hiren.

                  My Recent Article: - Way to know which control have raised PostBack
                  My Recent Tip/Trick: - Remove HTML Tag, get plain Text

                  J Offline
                  J Offline
                  Jeff Connelly
                  wrote on last edited by
                  #8

                  Hiren Solanki wrote:

                  Let me give you the strong need of property in C#. ... Property is introduced because of the changing requirement in software field.

                  Property was introduced just as a convenience, not because of any need. The change requirement could easily be implemented with normal methods as in C++. It's a quicker way to code for the developer, it's a quicker way to call for the consumer (no parentheses required), offers an auto-generation option, and signifies intent of the developer with fewer comments (a property is used when there is little calculation and no side effects). None of these are necessary though.

                  P K 2 Replies Last reply
                  0
                  • J Jeff Connelly

                    Hiren Solanki wrote:

                    Let me give you the strong need of property in C#. ... Property is introduced because of the changing requirement in software field.

                    Property was introduced just as a convenience, not because of any need. The change requirement could easily be implemented with normal methods as in C++. It's a quicker way to code for the developer, it's a quicker way to call for the consumer (no parentheses required), offers an auto-generation option, and signifies intent of the developer with fewer comments (a property is used when there is little calculation and no side effects). None of these are necessary though.

                    P Offline
                    P Offline
                    PIEBALDconsult
                    wrote on last edited by
                    #9

                    Also that Interfaces can specify properties, but not fields.

                    1 Reply Last reply
                    0
                    • J Jeff Connelly

                      Hiren Solanki wrote:

                      Let me give you the strong need of property in C#. ... Property is introduced because of the changing requirement in software field.

                      Property was introduced just as a convenience, not because of any need. The change requirement could easily be implemented with normal methods as in C++. It's a quicker way to code for the developer, it's a quicker way to call for the consumer (no parentheses required), offers an auto-generation option, and signifies intent of the developer with fewer comments (a property is used when there is little calculation and no side effects). None of these are necessary though.

                      K Offline
                      K Offline
                      kevinnicol
                      wrote on last edited by
                      #10

                      It also gives hints at what to look for when reflecting through an object. IE Some asp.net data grids will auto bind columns to all properties of an object.

                      J 1 Reply Last reply
                      0
                      • K kevinnicol

                        It also gives hints at what to look for when reflecting through an object. IE Some asp.net data grids will auto bind columns to all properties of an object.

                        J Offline
                        J Offline
                        Jeff Connelly
                        wrote on last edited by
                        #11

                        kevinnicol wrote:

                        Some asp.net data grids will auto bind columns to all properties of an object.

                        That's true and good point, but that's a .NET issue that wasn't applicable to C++.

                        modified on Friday, December 17, 2010 2:40 PM

                        K 1 Reply Last reply
                        0
                        • J Jeff Connelly

                          kevinnicol wrote:

                          Some asp.net data grids will auto bind columns to all properties of an object.

                          That's true and good point, but that's a .NET issue that wasn't applicable to C++.

                          modified on Friday, December 17, 2010 2:40 PM

                          K Offline
                          K Offline
                          kevinnicol
                          wrote on last edited by
                          #12

                          oops, thought I was in the C# forums, must have stumbled into the C++ forums by accident.

                          J 1 Reply Last reply
                          0
                          • K kevinnicol

                            oops, thought I was in the C# forums, must have stumbled into the C++ forums by accident.

                            J Offline
                            J Offline
                            Jeff Connelly
                            wrote on last edited by
                            #13

                            kevinnicol wrote:

                            oops, thought I was in the C# forums, must have stumbled into the C++ forums by accident

                            The point is to answer in context of the OP's questions, and if you had taken the time you spent on your clever sarcasm and spent it on reading all the OP's posts instead, you'd know he was coming from an OO background from C++. So I think you need to decide if you want to help someone with a question in context, or if you want to show off your mad skilz :) The OP said "I am wondering if that is a Microsoft's "invention" or a general OOP thinking. I never met it in C++." By way of my response to you, I was telling him that data grid data binding with properties is a Microsoft-specific invention for C#/.NET, and not general OOP thinking. I replied to your post to help him and the lurkers, not educate you. But as a token of goodwill, I'm still willing to educate you. You misused "IE" in your previous post. :) You might want to look that one up.

                            K 1 Reply Last reply
                            0
                            • J Jeff Connelly

                              kevinnicol wrote:

                              oops, thought I was in the C# forums, must have stumbled into the C++ forums by accident

                              The point is to answer in context of the OP's questions, and if you had taken the time you spent on your clever sarcasm and spent it on reading all the OP's posts instead, you'd know he was coming from an OO background from C++. So I think you need to decide if you want to help someone with a question in context, or if you want to show off your mad skilz :) The OP said "I am wondering if that is a Microsoft's "invention" or a general OOP thinking. I never met it in C++." By way of my response to you, I was telling him that data grid data binding with properties is a Microsoft-specific invention for C#/.NET, and not general OOP thinking. I replied to your post to help him and the lurkers, not educate you. But as a token of goodwill, I'm still willing to educate you. You misused "IE" in your previous post. :) You might want to look that one up.

                              K Offline
                              K Offline
                              kevinnicol
                              wrote on last edited by
                              #14

                              There was no sarcasm intended, I just saw your reply in my email and truly thought I had made a reply in the wrong forum. There was no intent of sarcasm or showing of my "mad skilz". I will choose to take your token of goodwill as that and not passive aggression; in the future will use eg. instead of ie. in those cases. Thanks.

                              J 1 Reply Last reply
                              0
                              • K kevinnicol

                                There was no sarcasm intended, I just saw your reply in my email and truly thought I had made a reply in the wrong forum. There was no intent of sarcasm or showing of my "mad skilz". I will choose to take your token of goodwill as that and not passive aggression; in the future will use eg. instead of ie. in those cases. Thanks.

                                J Offline
                                J Offline
                                Jeff Connelly
                                wrote on last edited by
                                #15

                                kevinnicol wrote:

                                There was no sarcasm intended

                                Oh sorry, my bad! :doh: Since you already know about e.g., you're ahead of 90% of the people out there....

                                T 1 Reply Last reply
                                0
                                • J Jeff Connelly

                                  kevinnicol wrote:

                                  There was no sarcasm intended

                                  Oh sorry, my bad! :doh: Since you already know about e.g., you're ahead of 90% of the people out there....

                                  T Offline
                                  T Offline
                                  Toli Cuturicu
                                  wrote on last edited by
                                  #16

                                  Everybody knows about exempli gratia and id est. They are learned in elementary school.

                                  J 1 Reply Last reply
                                  0
                                  • T Toli Cuturicu

                                    Everybody knows about exempli gratia and id est. They are learned in elementary school.

                                    J Offline
                                    J Offline
                                    Jeff Connelly
                                    wrote on last edited by
                                    #17

                                    ha ha yeah, right! If I only had a nickel for every time i.e. got misused.....

                                    1 Reply Last reply
                                    0
                                    Reply
                                    • Reply as topic
                                    Log in to reply
                                    • Oldest to Newest
                                    • Newest to Oldest
                                    • Most Votes


                                    • Login

                                    • Don't have an account? Register

                                    • Login or register to search.
                                    • First post
                                      Last post
                                    0
                                    • Categories
                                    • Recent
                                    • Tags
                                    • Popular
                                    • World
                                    • Users
                                    • Groups