CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Threaded View

  1. #2
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: Newb question. I am just begining to use C#

    Sometimes it makes sense to encapsulate data by making the main state of an object hidden, but accessible through properties. For example, suppose I wanted to represent a person with a name (string) and age (int). I might write:

    Code:
    public class Person
    {
        //Declare private variables; accessible only within this class
        private string name;
        private int age;
    
        //Constructor
        public Person(string newName, int newAge)
        {
            this.name = newName;
            this.age = newAge;
        }
    
        //Properties
    
        //Other classes can both get and set a Person's name
        public string Name
        {
            //Defines a getter method; always named get
            get { return this.name; }
    
            /*Define a setter method; always named set
             *The setter method will accept an argument (in this case a string)
             * that will be stored in a reserved variable (keyword) called value
            set { this.name = value; }
        }
    
        //But let's only let them get (NOT modify) age
        public int Age
        {
            //Define the getter
            get { return this.name; }
    
            //But omit the setter
        }
    }
    Make sense?
    Last edited by BioPhysEngr; February 15th, 2012 at 09:59 PM. Reason: wrong bbcode
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured