Click here to Skip to main content
Click here to Skip to main content

Properties

, 11 May 2007
Rate this:
Please Sign up or sign in to vote.
A tutorial on properties in C#

Introduction

Here we are going to introduce you to the concept of properties in C#. Properties can help simplify programming aspects. Let us understand what these programming aspects are and then understand how properties can be of help to simplify these programming aspects. Let us understand the programming aspects that properties intend to simplify, step by step through small programs.

What makes us use Properties?

Let's write a simple C# program that implements a class named Maths and contains an entry point function Main().

P1.cs

class Maths
{
  public static void Main ()
  {
  }
}

The program compiles successfully. Cool! Now let us add a private integer val to the class Maths.

P2.cs

class Maths
{
  private int val;
   
  public static void Main ()
  {
  }
}

Output

P2.cs(3,15): warning CS0169: The private field 'Maths.val' is never used

The program compiles successfully but it throws a warning message. The warning says that we haven't used the private variable val. We have just declared the variable val. So it's time to remove the warning. For this we need to assign value to the variable val. So let's define a new public member function SetVal() for the class Maths. This function will accept an integer as argument and assign it to the private variable val of the Maths class.

P3.cs

class Maths
{
  private int val;

  public static void Main ()
  {
  }

  public void SetVal ( int x )
  {
    val = x;
  }  
}

Output

Bingo! This program compiles successfully and that too without any warning message. The warning disappeared because the private variable val is used in the function SetVal(). Well, but what about the output? We didn't see any output. So let's go ahead and add a public member function Display() to the Math class above.

P4.cs

class Maths
{
  private int val;

  public static void Main ()
  {
  }

  public void SetVal ( int x )
  {
    val = x;
  }

  public void Display ( int x )
  {
    System.Console.WriteLine(val);
  }  
}

Output

This program compiles successfully but we don't get any output. That's because the Display() function is not invoked from within Main(). In order to invoke this function we need to create an object obj of class Maths in function Main() and invoke the function Display() on this object obj. This is what is done by the following program.

P5.cs

class Maths
{
  private int val;

  public static void Main ()
  {
    Maths obj = new Maths();
    obj.Display();
  }

  public void SetVal ( int x )
  {
    val = x;
  }

  public void Display()
  {
    System.Console.WriteLine(val);
  }  
}

Output

0

The program compiles and runs successfully to output the value of private member variable val which is 0. Now that we have functions Display() and SetVal() let's have another function GetVal(). This new function will return the value of the private integer member variable val. The new function is implemented by the following program.

P6.cs

class Maths
{
  private int val;

  public static void Main ()
  {
    Maths obj = new Maths();
    obj.Display();
  }

  public void SetVal ( int x )
  {
    val = x;
  }

  public void Display()
  {
    System.Console.WriteLine(val);
  }  

  public int GetVal ()
  {
    return val;
  }

}

Output

0

As expected the program compiles and runs successfully to output the value of private member variable val which is 0. Now that we have functions Display(), SetVal() and GetVal() let us use all of them in the above program by enhancing the Main() function. The enhanced program would look like this.

P7.cs

class Maths
{
  private int val;

  public static void Main ()
  {
    int y = 0;
    Maths obj = new Maths();
    obj.Display();
    obj.SetVal(10);
    y = obj.GetVal();
    System.Console.WriteLine(y);
    obj.SetVal(20);
    y = obj.GetVal();
    System.Console.WriteLine( y );
    obj.SetVal(30);
    y = obj.GetVal();
    System.Console.WriteLine( y );
  }

  public void SetVal ( int x )
  {
    val = x;
  }

  public void Display()
  {
    System.Console.WriteLine(val);
  }  

  public int GetVal ()
  {
    return val;
  }
}

Output

0
10
20
30

The program compiles and runs successfully. Inside Main() we create an object obj of class Maths and invoke the function Display() on this object obj. This outputs the value of private member variable val which is 0. Next SetVal() is invoked on obj which sets the value of the private member variable val to 10. Next a call is made to the function GetVal() which returns the value of the private member variable val which is 10. This is passed to the function System.Console.WriteLine() which displays 10 on the output screen. Next SetVal() is invoked on obj which sets the value of the private member variable val to 20. Next a call is made to the function GetVal() which returns the value of the private member variable val which is 20. This is passed to the function System.Console.WriteLine() which displays 20 on the output screen. Lastly, SetVal() is invoked on obj which sets the value of the private member variable val to 30. Next a call is made to the function GetVal() which returns the value of the private member variable val which is 30. This is passed to the function System.Console.WriteLine() which displays 30 on the output screen. This justifies the output of the above program.

In the above program, every time we had to set the value of the private member variable val we had to write the statements like

obj.SetVal(10);
obj.SetVal(20);
obj.SetVal(30);

Wouldn't it be of convenience if we could write the above statements as follows to achieve the same results?

obj.val = 10;
obj.val = 20;
obj.val = 30;

Certainly yes!

Similarly, in the above program, every time we had to get the value of the private member variable val we had to write the statements like

y = obj.GetVal();
y = obj.GetVal();
y = obj.GetVal();

Wouldn't it be of convenience if we could write the above statements as follows to achieve the same results?

y =obj.val ;
y =obj.val ;
y =obj.val ;

Certainly yes!

But hold on! Didn't you notice that val a private member variable of class Maths? So we cannot access val using statements like obj.val = 10; AND y =obj.val ;

from the Main() function of the class Maths. So whats the alternative? The alternative is to go for Properties.

Let's use Properties

We will define a property for the private member variable val and then access val using the property. Lets suppose that we define a property named Val for the private member variable val, then we will use the following statements to set and get the value of private member variable val.

obj.Val = 10;   
y =obj.Val ;

Doesn't this look very handy? Certainly it does! So let's enhance the above program to make use of Properties. Let's do things step by step. Our first step is to remove the functions Display(), SetVal(), GetVal() and their associated calls from the above program. On doing so the program would look like this:

P8.cs

class Maths
{
  private int val;

  public static void Main ()
  {
    int y = 0;
    Maths obj = new Maths();
  }

}

Output

P8.cs(7,10): warning CS0219: The variable 'y' is assigned but its value is 
    never used
P8.cs(3,15): warning CS0169: The private field 'Maths.val' is never used

For now let us live with the warnings. Now let's enhance the above program by adding a property Val. The purpose of this property Val would be to allow us to set and get the value of the private member variable val of the class Maths. The enhanced program would look like this:

P9.cs

class Maths
{
  private int val;

  public static void Main ()
  {
    int y = 0;
    Maths obj = new Maths();
  }

  public int Val 
  {
     get
     {
       return val;
     }
     set
     {
       val = value;
     }
   }
}

Output

P9.cs(7,9): warning CS0219: The variable 'y' is assigned but its value is never
        used

The program compiles successfully. This time it throws only one warning. The code in the bold font represents the property Val. Observe that a property is a definition, and looks like a function definition except that a function has opening and closing parenthesis. So a function of name func would look like this:

int  func ()
{
   //code
}

Observe the parenthesis in bold above. Now imagine how would a property of name func look like? Simple! Just remove the parenthesis we included above. So the property named func would look like this:

int  func 
{
   //code
}

Observe the absence of parenthesis in the property definition above.

Now let's have a look at the program above. It defines a property Val as follows:

public int Val
{
  //code
}

Simple isn't it?

Now let's focus on the code inside the property Val.

  public int Val 
  {
     get
     {
       return val;
     }
     set
     {
       val = value;
     }
   }

It contains two accessors named get and set. Accessors are defined exactly like properties except that they don't have return types. For example, the property Val that we defined had a return value of int.

Now let us focus on the get accessor.

get
{
    return val;
}

As mentioned earlier, the get accessor has no return type as well as no parenthesis. The code for the get accessor is present in the curly braces. The get accessor returns the private member variable val.

Now let us focus on the get accessor.

set
{
    val = value;
}

As mentioned earlier, the set accessor has no return type as well as parenthesis. The code for the set accessor is present in the curly braces. The set accessor sets the private member variable val to the value of variable value.

Lastly, let us understand value. Well, value is not a variable that we defined in any of the classes or functions that we wrote. value is a created by C# inside set accessor invisibly. It gets the value of that is assigned to the property in our case Val. We will see this shortly.

Now let's enhance the above program to put the defined property to use as well as add a PREVIOUS function Display() that would do the job of displaying the value of the private member variable val.

P10.cs

class Maths
{
  private int val;

  public static void Main ()
  {
    int y = 0;
    Maths obj = new Maths();
    obj.Val = 100;
    y = obj.Val;
    obj.Display();     
  }

  public void Display()
  {
    System.Console.WriteLine(val);
  }  

  public int Val 
  {
     get
     {
       return val;
     }
     set
     {
       val = value;
     }
   }
}

Output

100

The above program compiles and runs successfully to output the value of the private member variable val which is 100. The program proves that we were successful in using properties. When the following statement is getting executed:

obj.Val = 100;

the set accessor that belongs to property Val gets executed, i.e. the code inside it gets executed. There is only one statement in the set accessor and that is:

val = value;

This code assigns the value of variable value to the private member variable val. The variable value as mentioned earlier is created by C# inside the set accessor invisibly. It gets the value that is assigned to the property Val. The value assigned to the property Val of object obj is 100. So the value of the variable value is 100.

Let us enhance the above program by adding some print statements to get a firm grip.

P11.cs

class Maths
{
  private int val;

  public static void Main ()
  {
    int y = 0;
    Maths obj = new Maths();
    System.Console.WriteLine("Before set call");
    obj.Val = 100;
    System.Console.WriteLine("After set call");
    System.Console.WriteLine("Before get call");
    y = obj.Val;
    System.Console.WriteLine("After get call");
    obj.Display();     
  }

  public void Display()
  {
    System.Console.WriteLine(val);
  }  

  public int Val 
  {
    get
     {
       System.Console.WriteLine("Inside get");
       return val;
     }
     set
     {
       System.Console.WriteLine("Inside set");
       val = value;
     }
   }
}

Output

Before set call
Inside set
After set call
Before get call
Inside get
After get call
100

The above program compiles and executes successfully. The output clearly proves that when the following statement is getting executed:

obj.Val = 100; 

the set accessor that belongs to property Val gets executed i.e the code inside it gets executed.

The output also clearly proves that when the following statement is getting executed:

y =obj.Val;

the get accessor that belongs to property Val gets executed i.e. the code inside it gets executed.

With this I hope that you have understood the basic concept of property. Now let's go through a simple exercise to gain a firm understanding of property.

Let us define a class called cable. Inside this class let us have a private member variable length. We will need to get access to the length of the cable. So we need to define a property for the class cable. Let the name of the property be Length. The property Length will help us to set the value of length as well as get the value of length. So the Length property will have set as well as get accessors. Now, inside Main we will create an object of class cable. We will name this object as CoaxialCable. Using the property Length we will set its value to 100. Based on what we have studied so far the program will look like this…

P12.cs

// Class cable
class cable
{
  private int length;

  public static void Main ()
  {
    int y = 0;
    cable CoaxialCable = new cable();
    System.Console.WriteLine("Before set call");
    CoaxialCable.Length = 100;
    System.Console.WriteLine("After set call");
    System.Console.WriteLine("Before get call");
    y = CoaxialCable. Length;
    System.Console.WriteLine("After get call");
    obj.Display();     
  }

  //Display function to display the private member variable length
  public void Display()
  {
    System.Console.WriteLine(length);
  }  

  //Property Length
  public int Length 
  {
    get
     {
       System.Console.WriteLine("Inside get");
       return val;
     }
     set
     {
       System.Console.WriteLine("Inside set");
       val = value;
     }
   }
}

Output

Before set call
Inside set
After set call
Before get call
Inside get
After get call
100

By now the above program must have become a self-explainatory one for you. So let's move on…

Read Only Properties

Read Only Properties are the properties with only get accessor and no set accessor. Checkout the following program.

P13.cs

class cable
{
  private int length;

  public static void Main ()
  {
    int y = 0;
    cable CoaxialCable = new cable();
    System.Console.WriteLine("Before get call");
    y = CoaxialCable. Length;
    System.Console.WriteLine("After get call");
    obj.Display();     
  }

  public void Display()
  {
    System.Console.WriteLine(length);
  }  

  public int Length 
  {
    get
     {
       System.Console.WriteLine("Inside get");
       return val;
     }
   }
}

Output

Before get call
Inside get
After get call
0

The above program compiles and runs successfully. Observe that property Length defined in the above program is a read-only property as it has only one get accessor.

Write Only Properties

Write Only Properties are the properties with only set accessor and no get accessor. Checkout the following program.

P14.cs

class cable
{
  private int length;

  public static void Main ()
  {
    int y = 0;
    cable CoaxialCable = new cable();
    System.Console.WriteLine("Before set call");
    CoaxialCable.Length = 100;
    System.Console.WriteLine("After set call");
    obj.Display();     
    System.Console.WriteLine("Before set call");
    CoaxialCable.Length = 200;
    System.Console.WriteLine("After set call");
    obj.Display();     
  }

  public void Display()
  {
    System.Console.WriteLine(length);
  }  

  public int Length 
  {
    set
     {
       System.Console.WriteLine("Inside set");
       val = value;
     }
   }
}

Output

Before set call
Inside set
After set call
100
Before set call
Inside set
After set call
200

The above program compiles and runs successfully. Observe that property Length defined in the above program is a write-only property as it has only one set accessor.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Chetan Kudalkar
Software Developer (Senior)
India India
I am a Software engineer with around 7+ years of experience. Most of my experience is in Storage technology.

Comments and Discussions

 
Generalsome code error Pinmembercgliang12-Nov-08 22:30 
GeneralExcellent tutorial Pinmemberguerrilla200719-Nov-07 6:18 
GeneralFunction inside property PinmemberNavaneeth.21-Jun-07 23:33 
GeneralRe: Function inside property PinmemberInitri3-Mar-09 3:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 11 May 2007
Article Copyright 2007 by Chetan Kudalkar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid