Suppose we have the code below. I want to access the element that is highlighted by a comment in the Main() method in the class that has an indexer. The indexer also has a comment in the "set" section of the indexer code describing where the element is to be accessed. If I am missing something, any advice would be much appreciated.
Main():
arrayaccess aa = new arrayaccess();
string a = "karl";
if (a is string)
Console.WriteLine(aa[a]);
else
{
double d = Convert.ToDouble(a);
d = Math.Floor(d);
Console.WriteLine(aa[Convert.ToByte(d)]);
}
//set code
aa[3] = "karl";//the name (string) karl is to be accessed in the indexer of "ArrayClass" class.
class arrayaccess
{
private string[] names = new string[] { "carl", "karl", "doe", "john" };
public string this[object index]
{
get
{
if (index is string)
{
if (names.Contains(index))
return "found";
else return "not found";
}
else
{
if (Convert.ToByte(index) >= names.Length)
throw new IndexOutOfRangeException("Index should be less than or equal to 3");
return names[Convert.ToByte(index)];
}
}
set
{
//it's easy to do with the get accessor
if (names.Contains(/*value here*/))//want to access here
throw new ArgumentException("Sorry, duplicate"
"values not allowed");
else names[Convert.ToByte(index)] = value;
}
}
}
CodePudding user response:
Use the "value" keyword in your code:
if(names.Contains(value))