Reputation: 3415
in the following indexer code block, why do we need:
public string this[int pos]
{
get
{
return myData[pos];
}
set
{
myData[pos] = value;
}
}
what exactly does "this" in this[int pos] do? Thanks
/// Indexer Code Block starts here
using System;
/// <summary>
/// A simple indexer example.
/// </summary>
class IntIndexer
{
private string[] myData;
public IntIndexer(int size)
{
myData = new string[size];
for (int i = 0; i < size; i++)
{
myData[i] = "empty";
}
}
public string this[int pos]
{
get
{
return myData[pos];
}
set
{
myData[pos] = value;
}
}
static void Main(string[] args)
{
int size = 10;
IntIndexer myInd = new IntIndexer(size);
myInd[9] = "Some Value";
myInd[3] = "Another Value";
myInd[5] = "Any Value";
Console.WriteLine("\nIndexer Output\n");
for (int i = 0; i < size; i++)
{
Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
}
}
}
Upvotes: 1
Views: 350
Reputation: 144122
From a c# syntax perspective:
You need this
because - how else would you declare it? Functionality on a class must have a name, or address, by which to reference it.
A method signature is:
[modifiers] [type] [name] (parameters)
public string GetString (Type myparam);
A property signature is:
[modifiers] [type] [name]
public string MyString
A field signature is:
[modifiers] [type] [name]
public string MyString
Since an indexer has no name, it would not make much sense to write:
public string [int pos]
So we use this
to denote it's "name".
Upvotes: 3
Reputation: 564413
The "this" in your case specifies that this property is the indexer for this class. This is the syntax in C# to define an indexer on a class, so you can use it like:
myInd[9] = ...
Upvotes: 0
Reputation: 245429
It allows your class to behave in a similar manner to an array. In this case, your indexer is allowing you to reference myData transparently from outside the IntIndexer class.
If you didn't have the indexer declared, the following code would fail:
myInd[1] = "Something";
Upvotes: 0
Reputation: 124642
It means that you can use the indexer on the object itself (like an array).
class Foo
{
public string this[int i]
{
get { return someData[i]; }
set { someData i = value; }
}
}
// ... later in code
Foo f = new Foo( );
string s = f[0];
Upvotes: 4
Reputation: 32960
The 'this' keyword indicates that you are defining behavior that will be invoked when your class is accessed as if it was an array. Since your defining behavior for the class instance, use of the 'this' keyword in that context makes sense. You don't call myInd.indexer[], you call myInd[].
Upvotes: 0
Reputation: 3711
This is just marker for compiler to know that that property has indexer syntax.
In this case it enables myInd to use "array syntax" (e.g. myInd[9]).
Upvotes: 2