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. Re-Get and Set Property

Re-Get and Set Property

Scheduled Pinned Locked Moved C#
questioncsharphelp
5 Posts 5 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.
  • U Offline
    U Offline
    User 11127370
    wrote on last edited by
    #1

    Hi, I want to know that what is get and set Property in C#, and what is difference between them???And if i want to use only get Property then how can i do this in code??? Can any one help??? What is the use of get and set property,and why we have to use get and set property and which condition???

    P OriginalGriffO V B 4 Replies Last reply
    0
    • U User 11127370

      Hi, I want to know that what is get and set Property in C#, and what is difference between them???And if i want to use only get Property then how can i do this in code??? Can any one help??? What is the use of get and set property,and why we have to use get and set property and which condition???

      P Offline
      P Offline
      Peter Leow
      wrote on last edited by
      #2

      Check this out: Using Properties (C# Programming Guide)[^]

      1 Reply Last reply
      0
      • U User 11127370

        Hi, I want to know that what is get and set Property in C#, and what is difference between them???And if i want to use only get Property then how can i do this in code??? Can any one help??? What is the use of get and set property,and why we have to use get and set property and which condition???

        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #3

        Property get lets you retrieve the value of the property by calling a method to evaluate the property's current value, with syntactic sugar to make it look like a variable. Property set does the same thing, but it allows you to set the value. For example, your class may store the user information as "first name" and "second name" internally, and provide a Property FullName:

        private string firstName = "";
        private string lastName = "";
        public string FullName
        {
        get { return string.Format("{0} {1}", firstName, lastName); }
        set
        {
        string[] parts = value.Split(' ');
        if (parts.Length != 2) throw new ArgumentException("Full name requires a first and last name: " + value);
        firstName = parts[0];
        lastName = parts[1];
        }
        }

        To provide a getter only is easy - there are two ways:

        public string MyProperty { get { return "Hello"; }}

        Requires no setter. Or you could have a private setter:

        private string _MyProperty = "Hello";
        public string MyProperty
        {
        get { return _MyProperty; }
        private set { _MyProperty = value; }
        }

        This allows your class to set the value, but the outside world can only see the getter.

        Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        1 Reply Last reply
        0
        • U User 11127370

          Hi, I want to know that what is get and set Property in C#, and what is difference between them???And if i want to use only get Property then how can i do this in code??? Can any one help??? What is the use of get and set property,and why we have to use get and set property and which condition???

          V Offline
          V Offline
          V 0
          wrote on last edited by
          #4

          a small example on top of the previous answers. Think of a car, it has properties like color, max speed, current speed, number of wheels, ... A car can also do stuff like accelerate, turn, ... If you would put this in the code, the properties would be put in variables and exposed via properties (get/set). Accelerate and turn are actions that are translated into methods. Some properties can only be set when instantiating the class, eg number of wheels and maxspeed. Some can be changed from outside: You can repaint the car eg. Some can never be changed (number of wheels) and some can only be changed by using a method. (Accelerate will change the current speed and a check will prevent it from becoming higher than the max speed property). The inner workings of properties and methods are never exposed. eg. the check where the current speed is never higher than the max speed could reside in the accelerate method or in the current speed property itself. Read up on "encapsulation" for more info. Hope this helps.

          V.
          (MQOTD rules and previous solutions)

          1 Reply Last reply
          0
          • U User 11127370

            Hi, I want to know that what is get and set Property in C#, and what is difference between them???And if i want to use only get Property then how can i do this in code??? Can any one help??? What is the use of get and set property,and why we have to use get and set property and which condition???

            B Offline
            B Offline
            BillWoodruff
            wrote on last edited by
            #5

            At the risk (to my immortal soul) of appearing to re-write code by my esteemed mentor and colleague, OriginalGriff, I'd like to add that there is almost a "standard practice" in the use of Properties in .NET, for example:

            public class Employee
            {
            public Employee()
            {

            }
            
            public void SetEmployeeName(int authorizationcode, string fname, string lname)
            {
                if(AuthorizeOkay(authorizationcode)
                {
                    FirstName = fname;
                    FamilyName = lname;
                }
                else
                {
                    NotifyUnauthorizedAccess(authorizationcode);
                }
            }
            
            private string \_firstName;
            public string FirstName
            {
                private set { \_firstName = value; }
                get { return \_firstName; }
            }
            
            private string \_familyName;
            public string FamilyName
            {
                private set { \_familyName = value; }
                get { return \_familyName; }
            }
            
            public string FullName
            {
                get { return string.Format("{0}, {1}", FirstName, FamilyName); }
            }
            

            }

            Notes: 1. the variables declared 'private which begin with an underscore character "_" are called "backing fields." 2. the fact that all the 'get methods in the properties are public allows access by all. 3. the use of private 'set methods insure that the data can be changed only using the publicly exposed 'SetEmployeeName method. 4. the code shows a simulation in pseudo-code of the use of an "authorization code" to illustrate the idea that some vital information may be protected from "unauthorized" access. I'm not saying you "should" do anything like that, just suggesting the possibility. You might be asking why there are separate properties for first-name and family-name; consider you have a million records and you want to search for duplicate employee last names: possibly, easier to do with only one "field" to search in each record. Sure, there are lots more "bells and whistles" you could add here: for example, testing in the 'SetEmployeeName method for null values in either first, or family, name input strings. There are tools, like ReSharper, that will let you click on an auto-property name and will create the private backing field and modified set/get methods for you.

            «I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center

            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