Stellar Sword
Stellar Sword

Reputation: 6216

The C# this[] bracket constructor

I found in another library that you can call class instances using all sorts of parameters...

They used a this[int y, int z] format.

I tried to replicate it, but I can't find anything in any C# website.

class xx
    {
        private int _y { get; private set; }
        private int _z { get; private set; }
        public xx this[int y, int z] { get; set; }
        public xx(int y, int z){
            _y = y;
            _z = z;
        }
    }


    xx z = new xx(1, 2);
    xx y = xx[1, 2];

I'm trying to figure out, how to use this this[options] format. (The above code is totally wrong)

It would make things easier to not have to establish new instances each time.

Instead of going:

Column y = new Column(1, "value", "attributes;attribute;attribute");
FullTable.Add(y);

I could do:

FullTable.Column[1, "value", "attributes;attribute;attribute"]; // can get the instance or create it.

and it would already be instantiated and everything.

Anyway how would an OOP guru do this? Any ideas at all please?

Upvotes: 0

Views: 354

Answers (2)

Karl Anderson
Karl Anderson

Reputation: 34844

It is called an indexer and is used to reference an item in your class.

For example, suppose you wanted to write a program that organized your DVD movie collection. You could have a constructor for creating DVD movies to put into the collection, but it would be useful to "get" a DVD movie by an ID, which an indexer would allow for.

public class MovieCollection
{
    private Dictionary<string, Movie> movies = 
               new Dictionary<string, string>(); 
    private Dictionary<int, string> moviesById = 
               new Dictionary<int, string>();

    public MovieCollection()
    {

    }

    // Indexer to get movie by ID
    public Movie this[int index]  
    {
        string title = moviesById[index];
        return movies[title];
    }
}

Upvotes: 3

Tim S.
Tim S.

Reputation: 56546

The this[int x] syntax is called an indexer. It's how you can implement the sort of thing used in arrays, lists, and dictionaries to let you do, e.g. myList[0]. It cannot be used as a constructor, you should just use the ordinary constructor syntax you already know for that.

Upvotes: 3

Related Questions