Saturday, November 13, 2010

Properties in C#


Today my friend asked me a question for which i provided a solution using properties of the class. but then he asked me what are these properties, why to use them and how to Implement them To answer these questions

Definition:
Properties are named members of classes, structs, and interfaces. They provide a flexible mechanism to read, write, or compute the values of private fields through accessors. or we can say Properties equip a class with a public way to expose its private members or to get and set values for those private members, while hiding implementation or verification code.
A property has two accessors
  • Get
  • Set

The get keyword
with the help of this keyword we can define an accessor method for a property or an indexer which retrieves the value of the property or the indexer element.
The Set Keyword
With the help of this keyword we can define which accessor is used to assign a new value to the property or indexer.
The value keyword is used to define the value being assigned by the set accessor. Properties which do not implement a set accessor are termed as read only Properties.

Let’s take the first example to demonstrate how to declare and use read/write properties.

Example 1
This sample shows a Car class that has two properties: Name (string) and Model (int). Both properties have read/write attributes.


//car.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
classCar
    {
privatestring CarName = "N/A";
privateint CarModelNo = 0;
// Declare a Name property of type string:
publicstring Name
        {
get
            {
//returns the Carname
return CarName;
            }
set
            {
//set the value od carname provided by the user
                CarName = value;
            }
        }
// Declare an Age property of type int:
publicint ModelNo
        {
get
            {
//returns the CarModelNo
return CarModelNo;
            }
set
            {
//sets the value for CarModelNo
                CarModelNo = value;
            }
        }
//Overriding the ToString function of the class for demonstration
publicoverridestring ToString()
        {
return"Name = " + Name + ", ModelNo = " + ModelNo;
        }
publicstaticvoid Main()
        {
Console.WriteLine("Simple Properties");
// Create a new Car object:
Car mycar = newCar();
// Print out the name and the modelno associated with the car:
Console.WriteLine("Car details - {0}", mycar);
// Set some values on the car object:
            mycar.Name = "Maurti";
            mycar.ModelNo = 1;
Console.WriteLine("Car details - {0}", mycar);
// Increment the modelno property:
            mycar.ModelNo += 1;
Console.WriteLine("Car details - {0}", mycar);
Console.Read();
        }

    }
}
Output
Simple Properties
Car details - Name = N/A, ModelNo = 0
Car details - Name = Maruti, ModelNo =
Person details - Name = Joe, ModelNo = 100

Code Discussion
  • Notice the way that the properties are declared, for example, consider the Name property:

publicstring Name
        {
get
            {
return CarName;
            }
set
            {
                              CarName = value;
            }
        }
  • After declaring the property Set and Get methods are contained inside the declaration. We can control a property is read/write, read-only, or write-only by controlling Get or Set methods. If we only include Get Method the property will be read only if only set method is used the property will be write only (Although very less scenarios I have seen this), and as in our example if both Get and Set are used that means property is read/write.
  • Once the properties are created or declared, they can be used as if they are the members of that class. The following statementssows both getting and setting the value of a property

mycar.Name = "Maurti";
mycar.ModelNo = 1;

  • If you have noticed that in a property’s Set method a special value variable is available which we have not declared anywhere. This variable contains the value that the user has specified, for example:

CarName = value;

  • You can see that these properties are used as other variables only see how we have incremented the ModelNo property

mycar.ModelNo += 1;

  • The ToString() method is overridden in this example:
publicoverridestring ToString()
        {
return"Name = " + Name + ", ModelNo = " + ModelNo;
}
Check that I have not used the ToString() explicitly. It is invoked by default by the WriteLine calls.


In my next article I will  discus Abstract Properties

you can read Properties in C# here

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner

MSDotnetMentor

MSDotnetMentor My Website http://msdotnetmentor.com