Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I overload the [] operator in C# [duplicate]

I would like to add an operator to a class. I currently have a GetValue() method that I would like to replace with an [] operator.

class A {     private List<int> values = new List<int>();      public int GetValue(int index) => values[index]; } 
like image 469
Adam Tegen Avatar asked Jan 08 '09 15:01

Adam Tegen


People also ask

Can [] operator be overloaded?

In the following example, a class called complx is defined to model complex numbers, and the + (plus) operator is redefined in this class to add two complex numbers. where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .

What does overloading the [] operator do?

The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.

Can we overload [] in C++?

1) Overloading of [] may be useful when we want to check for index out of bound. 2) We must return by reference in function because an expression like “arr[i]” can be used an lvalue. Following is C++ program to demonstrate overloading of array index operator [].

How do you overload an operator?

To overload an operator, we use a special operator function. We define the function inside the class or structure whose objects/variables we want the overloaded operator to work with.


1 Answers

public int this[int key] {     get => GetValue(key);     set => SetValue(key, value); } 
like image 113
Florian Greinacher Avatar answered Oct 06 '22 07:10

Florian Greinacher