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?
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.
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.
'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.
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.
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;
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With