Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The 'this' keyword as a property

Tags:

I know C# well, but it is something strange for me. In some old program, I have seen this code:

public MyType this[string name]
{
    ......some code that finally return instance of MyType
}

How is it called? What is the use of this?

like image 730
viky Avatar asked Mar 25 '10 16:03

viky


People also ask

What is the this keyword in C#?

this (C# Reference) The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.

Why do you use this in C#?

The this keyword is used to reference the current instance of a class, or an object itself, if you will. It is also used to differentiate between method parameters and class fields if they both have the same name.

What kind of class methods Cannot use the this keyword C#?

'this' keyword is used to represent the current instance of a class. If instance variables and method parameters have the same name then 'this' keyword can be used to differentiate between them. 'this' can be used to declare indexers. We cannot use 'this' in a static method.

What is get set in C#?

The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property. If you don't fully understand it, take a look at the example below.


2 Answers

It is indexer. After you declared it you can do like this:

class MyClass
{
    Dictionary<string, MyType> collection;
    public MyType this[string name]
    {
        get { return collection[name]; }
        set { collection[name] = value; }
    }
}

// Getting data from indexer.
MyClass myClass = ...
MyType myType = myClass["myKey"];

// Setting data with indexer.
MyType anotherMyType = ...
myClass["myAnotherKey"] = anotherMyType;
like image 104
Andrew Bezzub Avatar answered Oct 01 '22 11:10

Andrew Bezzub


This is an Indexer Property. It allows you to "access" your class directly by index, in the same way you'd access an array, a list, or a dictionary.

In your case, you could have something like:

public class MyTypes
{
    public MyType this[string name]
    {
        get {
            switch(name) {
                 case "Type1":
                      return new MyType("Type1");
                 case "Type2":
                      return new MySubType();
            // ...
            }
        }
    }
}

You'd then be able to use this like:

MyTypes myTypes = new MyTypes();
MyType type = myTypes["Type1"];
like image 35
Reed Copsey Avatar answered Oct 01 '22 11:10

Reed Copsey