Classes

Properties and Indexers

Properties

If it is neccesary to access a private field in a class, it is possible to do it using a Property. A property is the representation of some field inside the class. The signature must have its name, its type, and the reserved keywords value, get, set and return, and also must be public. Here is an example:

 public int NameofProperty {

	// First part -- We return the value 
	get 
	{
		return this.someIntField;
	}

	// Second part -- We set the value assigned to this property
	set
	{
		this.someIntField = value;
	}
 }
In this example, we created a int property for a field, called someIntField. Note that it is possible to use the first adn second parts for different fields.

Int the first part there is a sentence block after the reserved word get. The get keyword marks the begin of the output specification. If some extern element want to access the value of the property, it will get as return the value of some intern field ( in this case, someIntField ).

In the second part, there's another block sentence, this time after the set keyword. This word marks the begin of the input specification. If some extern element wants to assign a certain value to a our property, it will be able to set the value to a certain field. The value keyword references to the value passed when assigning a value to the property.

Note that sometimes the second part doesn't appear and the property becomes read-only.

The best way of learning if coding. Let's write a small example. There will be a class, PropertyTest, which will have a private field, called field, of type int. It will also have a property, called Field ( the developers usually create a property A for an a field, or a Var property for a var field, and so on ).

//
// Using properties
//
using System;

 public class PropertyTest {

	// The private field
	int field;

	// The property
	public int Field {

		get
		{
			return this.field;
		}

		set
		{
			this.field = value;
		}

	}

 }

 public class Tester {

	public static void Main () {

		PropertyTest t = new PropertyTest();
	
		// Won't work
		//t.field = 56;

		// It will work
		t.Field = 108;

		// It won't work
		// Console.WriteLine(" The value of field is {0}", t.field);

		// It will work
		Console.WriteLine(" The value of Field is {0}", t.Field);
		

	}

 }

Save, compile and run it. You should get:

 The value of Field is 108
Try to decomment the wrong lines, and you should get something like:
temp3.cs(35) error CS0122: `PropertyTest.field' is inaccessible due to its protection level
temp3.cs(41) error CS0122: `PropertyTest.field' is inaccessible due to its protection level