Properties, Arrays and Indexers

author-image
CIOL Bureau
Updated On
New Update

Sonali Gogate

Sonali Gogate

Properties

In C#, properties are first class citizens. They appear as fields to the user
but use a member function to get and set the value. A property has a declaration
and either one or two blocks of code — known as accessors — to get and set
the property.

Advertisment

A simple example —

Defining a property.


class MyClass
{
	private string myname;
	public string MyName
	{
		get
		{“
			return myname;
		}
		set
		{
			myname = value;	// value is a special parameter
}				// containing the actual value
	}
}

Here is how one would use this property —

MyClass mclass  = new MyClass();
mclass.MyName = “Ajay Joshi”;		// set the property
string somename = mclass.MyName;	// get the property

Properties separate the interface of a class from the implementation of the
same. The advantage of using properties is that you can do some kind of
preprocessing (check for validity, do required manipulations, handle exceptions
etc.) before actually assigning the values, instead of letting the user assign
values blindly. You also manage to hide the data from the user.

Read only properties

There are times when you would like the user to read a value, but not set it.
For this purpose you can define a read only property.

To define a read only property, you would omit defining the set method for
the property.

For example if I defined the above property definition as follows, I would
get a read only property —


class MyClass
{
	private string myname;
	public string MyName
	{
		get
		{“
			return myname;
		}
	}
}
Advertisment

Inheriting properties

Just like methods, you can use virtual, override or abstract while defining
the properties. This enables a derived class to inherit and override properties
just like other members from the base class. One point to note is that these
modifiers can be used only at property level. That is, if you have a read/write
property then you can not override only the get method (or the set method).

Arrays

In C#, arrays are objects that have the System.Array class defined as
their base class.

Declaring Arrays

Here is how you declare an array —


int<> IntNums;

Another example -
// Declares and instantiates a single-
// dimensional array of 6 integers.
int<> numbers = new int<6>;

How ever, while declaring an array as a member of a class, it needs to be instantiated later at run time. Here is how —

class MyClass
{
	…
	int<> nums;
	…

	void MyInitMethod()
    	{
		…
		nums = new int<6>;
		…
	}
}

Single and Multi Dimensional Arrays

The arrays we saw in the section above were single dimensional ones.

The way you get to individual element of a single dimensional array is as
follows —

To get the element ‘i’ of nums
you would say nums — just like
in C or C++.

Multidimensional Arrays

You declare a multidimensional array by separating each dimension with a
comma. Here is an example —

int<,,> num3d;

The number of dimensions of an array is known asrank. And to
determine the rank programmatically you can make use of the Array.Rank
property.

Advertisment

So if you have —

int<> singleD;
int<,> doubleD;
int<,,> tripleD;

Then the following lines would determine the ranks of each —


singleD.Rank
doubleD.Rank
tripleD.Rank

And you would get 1, 2 and 3 respectively.

Jagged Arrays

A jagged array is an array of arrays.

Here is an example of defining a jagged array of integers (that is array of
integer arrays)


int<><> myJaggedArray;

Lets look at another example in more detail.

Let us see that I plan to have one jagged array to maintain names of week
days and months.

So I would declare —


string<><> DaysAndMonths;

Then I would specify how many string arrays are there as follows —


DaysAndMonths = new string<2><>;

And for each of the 2 I would specify the number of strings as follows —

Advertisment
DaysAndMonths<0> = string<7>; //
DaysAndMonths<1> = srtring<12>’ //

Now we can populate


DaysAndMonths<0> and DaysAndMonths<1>

independently
with day names and month names.

Note that the number of elements of


DaysAndMonths<0>
and the number of elements of DaysAndMonths<1>

would necessarily be different.

Indexers

Like most features of a programming language, the benefit of indexers comes
down to making your applications more intuitive to write.

Defining indexers is very similar to defining properties but for 2
differences — indexers take an index
argument and this keyword is used as
the name of the indexer.

Here is a detailed example of defining and using indexer —


using System;
using System.Collections;

class IListBox

{
    protected ArrayList datalist = new ArrayList();

    public object this
    {
        get
        {
            if (0 <= indx && indx < datalist.Count)
            {
                return (datalist);
            }
            else
            {
                // Possibly throw an exception here.
                return null;
            }
        }
        set
        {
            if (0 <= indx && indx < datalist.Count)
            {
                datalist = value;
            }
            else if (indx == datalist.Count)
            {
                datalist.Add(value);
            }
            else
            {
                // Possibly throw an exception here.
            }
        }
    }
}

class Indexers1App
{
    public static void Main()
    {
        IListBox ilbx = new IListBox();
        ilbx<0> = "Matt";
        ilbx<1> = "Dave";
        ilbx<2> = "Alex";
	…
    }
}
Advertisment

Arrays as we all know are a very useful data type and have been used
extensively in a lot of programming languages. Properties and Indexers are
useful in making programming more intuitive and easy. They also help us in
hiding the actual data and controlling the behavior of the data coming in and
going out.

tech-news