Properties, Array and Indexers in C#

Properties are generally used to encapsulate fields of a class. What if a property returns an array, that way we expose an array as property. That may result in accidently overwrite a lot of data as array are reference types. Let’s understand the whole scenario with an example:

Following structure exposes an array property named details.

struct Person

{

privatestring[] details;

publicstring[] Details

{

get { returnthis.details; }

set { this.details = value; }

}

}

Usage:

Person p = new Person();

string [] details = newstring[]{ "James","Kavin","Ramy" };

p.Details = details;

Consequences:

string[] refdetails = p.Details;

refdetails[0] = "James Modified";

refdetails[1] = "Kavin Modified"

refdetails[2] = "Ramy Modified";

Because array are reference types, the variable refdetails refers to the same object as private data variable in the Person structure. Any changes made to the elements in refdetails are made to the details directly. However, this problem can be solved by using Clone method in the get and set accessors of the Details property as shown below:

struct Person

{

privatestring[] details;

publicstring[] Details

{

get { returnthis.details.Clone() asstring[]; }

set { this.details = value.Clone() asstring[]; }

}

}

From the memory usage point of view, the described approach is quite expensive and messy.

Other Options:

Usage of Indexers, explained in my previous articles, is the better solution in this case i.e. don’t expose the entire array as a property rather make its individual element accessible through an Indexer.

struct Person

{

privatestring[] details;

publicstringthis[int i]

{

get { returnthis.details[i]; }

set { this.details[i] = value; }

}

}

The code below uses the indexer in a similar manner as described earlier with Properties:

Person p = new Person();

string [] details = newstring[]{ "James","Kavin","Ramy" };

p.Details = details;

Assignment:

string[] refdetails = newstring[3];

refdetails[0] = p[0];

refdetails[1] = p[1];

refdetails[2] = p[2];

Modifying:

refdetails[0] = "James Modified";

refdetails[1] = "Kavin Modified"

refdetails[2] = "Ramy Modified";

The advantage with indexers is that changing values in refdetails array has no effect on the original array. If you really want to modify elements in the Person class, use the statement as shown below: