Posted by : Sudhir Chekuri Saturday, 9 January 2016

The Set and Get methods of a property are contained inside the property declaration. You can control whether a property is read/write, read-only, or write-only by controlling whether a Get or Set method is included.

Example program for Set and Get properties

Program
using System;
namespace PropertiesExample
{
    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
            {
                myName = value;
            }
        }

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


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

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

            // Print out the name and the age associated with the person:
            Console.WriteLine(person.Name + " , " + person.Age);

            // Set some values on the person object:
            person.Name = "Joe";
            person.Age = 99;
            Console.WriteLine(person.Name + " , " + person.Age);

            // Increment the Age property:
            person.Age += 1;
            Console.WriteLine(person.Name + " , " + person.Age);

            Console.ReadKey();
        }
    }
}


Output

Simple Properties

N/A , 0

Joe , 99

Joe , 100

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Followers

Total Pageviews

Powered by Blogger.

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -