how do I make brackets [] take specific args (like the DataRow class)

  • Thread starter Thread starter Chris LaJoie
  • Start date Start date
C

Chris LaJoie

I'd like to impliment the same type of functionality the DataRow has as far
as how it uses brackets. I'll give you an example of what I'm looking for.

DataRow dr = dt.Rows[0];

string aTestVar = (string)dr[0];
....OR...
string aTestVar = (string)dr["aTestColumn"];

How would I impliment this in my own custom types? Thanks.

Chris LaJoie
 
Hi,

What you are refering to is called a indexer. In C# the syntax for an
indexer is like that of a property. The following is the indexer that takes
a int as the index and returns an object. Note that the indexer is named
this in C#. The type of the index and the return value can be what ever make
sense for your implemetation.

class MyData
{
public virtual object this[int index]
{
get {...}
set {...}
}
}

To use this

MyData d = new MyData()
string s = (string)d[2];

Hope this helps

Chris Taylor
 
Chris LaJoie said:
I'd like to impliment the same type of functionality the DataRow has as far
as how it uses brackets. I'll give you an example of what I'm looking for.

DataRow dr = dt.Rows[0];

string aTestVar = (string)dr[0];
...OR...
string aTestVar = (string)dr["aTestColumn"];

How would I impliment this in my own custom types? Thanks.

Use indexers:

public class MyClass
{
public string this[int index]
{
get { return // whatever you need to return based on index }
set { whatever = value; }
}
public string this[string match]
{
get { return // whatever you need to return based on match } // etc.
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top