Reputation: 2973
I am not able to proceed with the below code . Can anyone please help ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Demo_Inidexers
{
public class MyIndexer
{
Dictionary <int,string > testdctnry = new Dictionary<int,string>() ;
public string this[int index,string val ]
{
get
{
string temp;
if (index > 0)
MessageBox .Show ("Hey m Zero");
return testdctnry[index];
}
set
{
if (index > 1)
MessageBox.Show("Setting up");
testdctnry.Add(index, val);
}
}
}
static class Program
{
static void Main()
{
MyIndexer MI = new MyIndexer();
}
}
}
In the above code how can i use both indexer and dictionary . I am very new to c# , please help . i want to understand indexer .
Upvotes: 1
Views: 4242
Reputation: 203829
The value for setting an indexer shouldn't be used as the second argument. The get
simply has no access to a set value, as there is none. In the set
method there is a contextual keyword, value
, that has the value set to the indexer:
public class MyIndexer
{
private Dictionary <int,string> testdctnry = new Dictionary<int,string>();
public string this[int index]
{
get
{
if (index > 0)
MessageBox.Show("Hey m Zero");
return testdctnry[index];
}
set
{
if (index > 1)
MessageBox.Show("Setting up");
testdctnry[index] = value;
}
}
}
Upvotes: 3
Reputation: 124
What problem are you having?
You call indexers by calling obj[args]. To use the getter, you use obj[args] as if it were a value. To use the setter, you use obj[args] on the left side of an assignment.
http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx
Upvotes: -1