There are two ways to solve this problem
(1) Use Indexed Property as follows:
class A
{
object[] arr = {123, "Text" , 456.55};
public object this[int index]
{
get { return arr[index]; }//add proper checks on index bounds here
set { arr[index] = value; } //add proper checks on index bounds here
}
public static void Main()
{
A obj = new A();
Console.WriteLine(obj[1]); //displays "Text"
obj[2] = "SomeText";
Console.WriteLine(obj[2]); //displays "SomeText"
Console.Read();
}
}
This solution will use object name like an array.
(2) If you want to use a indexed property like
obj.ArrayItem[i] (where ArrayItem is a property using index as a parameter), there is no direct method for it in C#. A workaround is to write a wrapper class around the indexer property. Something like this:
public class A
{
public class ArrayItemClass
{
object[] arr = {123, "Text", 456.55};
public object this[int index]
{
get { return arr[index]; } //add proper checks on index bounds here
set { arr[index] = value; } //add proper checks on index bounds here
}
}
//create an object of class ArrayItem and initialize it in the constructor of class A
ArrayItemClass objArrayItem;
A() { objArrayItem = new ArrayItemClass(); }
//write a readonly property for allowing access to objArrayItem
public ArrayItemClass ArrayItem
{
get { return objArrayItem; }
}
public static void Main()
{
A obj = new A();
Console.WriteLine(obj.ArrayItem[1]); //will display "Text"
obj.ArrayItem[2] = "SomeText";
Console.WriteLine(obj.ArrayItem[2]) ; //will display "SomeText"
Console.Read();
}
}
Hope this helps.
--
Sameeksha,
MCP (.NET)
"Pradeep Kumar" wrote:
I have a scenario where I am writing a property(using get and set) have to return a member of an object stored in an array of objects! The class user has to pass an index based on which a object i's member is returned from the array.
How will the property be declared in C#?