Reputation: 77
Is there a way to do something like this:
class blabla
{
string[] a;
string ciao(int row, string text)
{
set { a[row] = text;}
get { return a[row;}
}
}
(yeah i know i can just make my own method eventually)
Upvotes: 0
Views: 260
Reputation: 62472
This best you can do is using the index property, this
:
class Foo
{
string[] row;
string this[int row]
{
set {a[row] = value;}
get {return a[row];}
}
}
Then, you access it using the []
operator:
Foo f;
f[1] = "hello";
It's not possible to have a named property that behaves this way.
As an interesting aside, there's no reason, from a .NET, that properties can't be parameterized. If you look at the PropertyInfo class you can see that a property is just a get method and a set method, both of which can take parameters. In fact this is how the index property works (along with an attribute). It's just that C# doesn't expose this functionality through the language.
Upvotes: 6
Reputation: 5106
You can make an indexer property
public string this[int index]
Overloads the [] operator on your class, allowing you to take a parameter between the [] and after the =
You could change the type of the index parameter, but this will probably be confusing to the caller.
http://msdn.microsoft.com/en-us/library/aa288464(v=vs.71).aspx
class blabla
{
private string[] a;
string this[int row]
{
set { a[row] = value;}
get { return a[row;}
}
}
The syntax works so that the type of value
is specified by the return type of the overloaded operator.
Upvotes: 1