Nano's Blog

01/02/2010

how properties are an integral part of the C# programming language – Part 1

Filed under: programming — Tags: , — nano @ 10:46

a Person class that has two properties: Name (string) and Age (int). Both properties are read/write.

// person.cs
using System;
class Person
{
    private string myName = "N/A";
    private int myAge = 0;

    // Declare a Name property of type string:
    public string Name
    {
        get
        {
            return myName;
        }
        set
        {
            // Note that in a property Set method a special value variable is available.
            // This variable contains the value that the user specified
            myName = value;
        }
    }

    // Declare an Age property of type int:
    public int Age
    {
        get
        {
            return myAge;
        }
        set
        {
            myAge = value;
        }
    }

    public override string ToString()
    {
        return "Name = " + Name + ", Age = " + Age;
    }

    public static void Main()
    {
        Console.WriteLine("Simple Properties");

        // Create a new Person object:
        Person person = new Person();

        // Name() and Age() called by the WriteLine()
        // Print out the name and the age associated with the person:
        // Notice that ToString is not explicitly used in the program.
        // It is invoked by default by the WriteLine calls.
        Console.WriteLine("Person details - {0}", person);

        // Set some values on the person object:
        person.Name = "Joe";
        person.Age = 99;
        Console.WriteLine("Person details - {0}", person);

        // Increment the Age property:
        // Notice the clean syntax for incrementing the Age property on a Person object:
        // the equivalent code might look like this: person.SetAge(person.GetAge() + 1);
        person.Age += 1;
        Console.WriteLine("Person details - {0}", person);
    }
}

Output:

Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100

- from msdn.com

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress