0

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)

DROP TABLE users
  • 1,955
  • 14
  • 26
user3161621
  • 75
  • 2
  • 8

2 Answers2

6

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.

Sean
  • 60,939
  • 11
  • 97
  • 136
  • 3
    Re aside: it's one of the features that [VB has](http://msdn.microsoft.com/en-us/library/bc3dtbky.aspx) and C# doesn't. – GSerg Jan 17 '14 at 17:32
  • 1
    I just tried to create a class in VB that has parameterized property `Bar` and reference it from a C# project. The class is shown by C#'s IntelliSense as having two separate methods, `get_Bar` and `set_Bar`. – GSerg Jan 18 '14 at 08:17
1

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.

MrFox
  • 4,852
  • 7
  • 45
  • 81