Steve Steve - 4 months ago 37
C# Question

Why can't I pass indexer as a ref parameter?

I understand the rule. But who knows why this is?

If my code is:

List<T> x = new List<T>;
x.Add(new T());
x.Add(new T());
x.Add(new T());

int y = 2;

//And I call a method
M1(ref x[y]);

ref x[y] is just a pointer to my instance of T of interest isn't it?

Why can't I write the line of code call it M1() in the very simple fashion.


I know the workaround:

T cX = x[y];
M1(ref cX);

I'm hoping to hear why the architects of c# require this extra step to pass a pointer? Or is it a compiler limitation?


An indexer value is not classified as a variable; therefore, you cannot pass an indexer value as a ref or out parameter.

Refer msdn