#246 – Implementing a Read-Only Property

You implement a read-only property in a class by implementing the get accessor, but not the set accessor.  This will allow client code to read the property’s value, but not write to it directly.

Below is an example of a read-only property for the Dog class.  The WhenLastBarked property returns a DateTime value indicating the last time that the Dog barked–i.e. the last time that someone called the Bark method.

    // Backing variable storing date/time last barked
    private DateTime lastBarked;

    // Public property, allows reading lastBarked
    public DateTime WhenLastBarked
    {
        get
        {
            return lastBarked;
        }
    }

    // Bark method also sets lastBarked
    public void Bark()
    {
        Console.WriteLine("{0}: Woof!", Name);
        lastBarked = DateTime.Now;
    }

We now have a property in the Dog class that we can read from, but not write to.

    kirby.Bark();
    DateTime whenHeBarked = kirby.WhenLastBarked;

Advertisement

#245 – Defining a Set Accessor for a Property

A set accessor for a property is the code that executes when the client of an object tries to write the property’s value.

The set accessor is defined using the set keyword.  The new property value is accessible using the value keyword, which is treated as a local variable having the same type as the property.

It’s common to store the value of a property in an internal private variable, known as the backing field.

In the example below, the set accessor for a property stores the new property value in the internal backing field whenever the property is written.  Note that the private variable and the public property name differ only in their case (name vs. Name).

    // Backing field--where the property value is actually stored
    private string name;

    public string Name
    {
        // Set accessor allows the property to be written
        set
        {
            name = value;
        }
    }

#244 – Defining a Get Accessor for a Property

A get accessor for a property is the code that executes when the client of the object tries to read the property’s value.

The get accessor is defined using the get keyword.  The get accessor should return a value of the same type as the property itself.  You often just return the value of an internal private variable, which is known as the backing field.

In the example below, we define a get accessor for a property and return the value of the internal backing field whenever the property is read.

    // Backing field--where the property value is actually stored
    private string name;

    public string Name
    {
        // Get accessor allows the property to be read
        get { return name; }
    }

Below is an example of the Name property being read.

    // Read the Name property
    string objectName = myObject.Name;

#243 – Property Get and Set Accessors

You can define a property in a class as a way of encapsulating a private field.  When declaring a property in a class, you define the property’s type, its name, and code for the property’s accessors.  The accessors are the means by which a user of the class reads and writes the property’s value.

When defining the accessors, you can have one of the following combinations:

  • Just a get accessor   (property is read-only)
  • Just a set accessor  (property is write-only)
  • Both get/set accessors  (property is read/write)

The get accessor defines the code that executes when some code tries to read the property’s value.

The set accessor defines the code that executes when a property value is written to.

#242 – Declaring and Using a Property in a Class

You can create instance data in a class by defining public fields.  You can read and write fields using a reference to an instance of the class.

A class more often exposes its instance data using properties, rather than fields.  A property looks like a field from outside the class–it allows you to read and write a value using a reference to the object.  But internally in the class, a property just wraps a private field, which is not visible from outside the class.

    public class Dog
    {
        // Private field, stores the dog's name
        private string name;

        // Public property, provides a way to access
        // the dog's name from outside the class
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

    }

Using the property:

            Dog kirby = new Dog();

            kirby.Name = "Kirby";

#241 – Declaring and Using Private Instance Methods

You can include a method in a class that is private.  It will be callable from other methods within the class, but not callable from outside the class.

In the example below, the PrintName method is visible from outside the class, but the PrintAge method can only be called from within the class.

    public class Dog
    {
        public string Name;
        public int Age;

        public void PrintName()
        {
            Console.Write(Name);
            PrintAge();
        }

        private void PrintAge()
        {
            Console.WriteLine(string.Format(" ({0})", Age));
        }
    }

Code that attempts to call the PrintAge method from outside the class will not compile.

            Dog kirby = new Dog();
            kirby.Name = "Kirby";
            kirby.Age = 14;

            kirby.PrintName();
            kirby.PrintAge();    // compiler error

#240 – Private and Public Instance Data in a Class

In a class, you can define public instance data, as fields.  Any instance of the class can read and write the instance data stored in these fields.

For example:

    public class Dog
    {
        public string Name;
        public int Age;
    }

    // Creating a Dog object
    Dog kirby = new Dog();
    kirby.Name = "Kirby";
    kirby.Age = 14;

You might, however, want to declare some instance data that is visible from within the class’ methods, but not visible outside the class.  You can do this by declaring a field as private.

        public string Name;
        public int Age;

        private DateTime lastPrint;

        public void PrintName()
        {
            Console.WriteLine(Name);

            // lastPrint is visible here
            lastPrint = DateTime.Now;
        }

This private field will not be visible from outside the class.

            Dog kirby = new Dog();
            kirby.Name = "Kirby";

            // Compiler error: inaccessible due to its protection level
            DateTime when = kirby.lastPrint;

#239 – The this Reference

In C#, the this keyword refers to the current instance of a class–i.e. the specific instance that an instance method was invoked on.

For example, assume that we have a Dog class and kirby is an instance of this class and that we invoke the Dog.PrintNameAndAge method as follows:

    kirby.PrintNameAndAge();

If the this keyword appears in the implementation of the PrintNameAndAge method, it refers to the kirby object.

        public void PrintNameAndAge()
        {
            Console.WriteLine("{0} is {1} yrs old", Name, Age);

            // Assume we have a static TrackDogInfo method in
            //   a DogUtilities class--and that it accepts a
            //   parameter that is a reference to a Dog object.
            DogUtilities.TrackDogInfo(this);
        }

We passed a reference to the kirby instance to the TrackDogInfo method.  It will therefore have access to all of the instance data in the kirby object, as stored in the object’s fields.

#238 – Call a Method from Another Method

You can call an instance method of a class from another instance method within that class.  The second method called will execute upon the same instance of the class for which the first method was called.

In the example below, we can call the Dog.Growl method, or the Dog.BarkAndGrowl method which in turn calls Growl.

    public class Dog
    {
        public string Name;
        public int Age;

        public void BarkAndGrowl()
        {
            Console.WriteLine("Woof.  --{0}", Name);
            Growl();
        }

        public void Growl()
        {
            Console.WriteLine("Grrr.  --{0}", Name);
        }
    }

Here’s an example of calling these methods on an instance of the Dog class.

            Dog kirby = new Dog();
            kirby.Name = "Kirby";

            kirby.Growl();      // Grrr.
            kirby.BarkAndGrowl();  // Woof.  Grrr.

#237 – Referencing Class Fields from Within One of its Methods

In any of the instance methods for a class, you can reference one of that class’ fields by just using the field name.  The value used will be the value stored in that field, for the object (instance of the class) that was used to invoke the method.

In the example below, we have Name and Age fields in the class.  The PrintNameAndAge method can just reference these fields by name to get their value for the current object.

    public class Dog
    {
        public string Name;
        public int Age;

        public void PrintNameAndAge()
        {
            Console.WriteLine("{0} is {1} yrs old", Name, Age);
        }
    }

We might call this method as follows:

            Dog kirby = new Dog();
            kirby.Name = "Kirby";
            kirby.Age = 15;

            // Prints "Kirby is 15 yrs old"
            kirby.PrintNameAndAge();