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
- {
- private string[] details;
- public string[] Details
- {
- get { return this.details; }
- set { this.details = value; }
- }
- }
- Person p = new Person();
- string [] details = new string[]{ "James","Kavin","Ramy" };
- p.Details = details;
- string[] refdetails = p.Details;
- refdetails[0] = "James Modified";
- refdetails[1] = "Kavin Modified"
- refdetails[2] = "Ramy Modified";
- struct Person
- {
- private string[] details;
- public string[] Details
- {
- get { return this.details.Clone() as string[]; }
- set { this.details = value.Clone() as string[]; }
- }
- }
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
- {
- private string[] details;
- public string this[int i]
- {
- get { return this.details[i]; }
- set { this.details[i] = value; }
- }
- }
- Person p = new Person();
- string [] details = new string[]{ "James","Kavin","Ramy" };
- p.Details = details;
- Assignment:
- string[] refdetails = new string[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";
- p[0] = "James Modified";
- p[1] = "Kavin Modified"
- p[2] = "Ramy Modified";

Santhakumar MunuswamyPosted Aug 18, 2015, 2:49 PM
Nice one
Nilesh JadavPosted Aug 17, 2015, 4:26 AM
Good one on Properties