Mr. Smith
Mr. Smith

Reputation: 4506

Does a C# indexer return a variable or value?

Mutable structs are error-prone; dictionary[0].Inflate(1,1) doesn't behave the same as array[0].Inflate(1,1) would when T is a Rectangle (since array[0] is a variable, whereas dictionary[0] is a value).

If I make a custom indexer for SomeClass:

public T this[int x, int y] { get { return arr[y*100+x]; } }

Is someclass[x,y] a variable or value or neither? Presuming T is, of course, a struct.

Upvotes: 1

Views: 286

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500665

An indexer access expression is initially classified as an "indexer access". From section 7.6.6.2 of the C# 4 spec:

The result of processing the indexer access is an expression classified as an indexer access

And then from section 7.1:

A property access or indexer access is always reclassified as a value by performing an invocation of the get-accessor or set-accessor.

So basically you can think of it as being classified as a value.

However, an array access is classified as a variable expression. From section 7.6.6.1 of the C# 4 spec:

The result of evaluating an array access is a variable of the element type of the array [...]

That's why this is fine:

string[] x = { "", "", "" };
SomeMethodWithRef(ref x[0]);

But this isn't:

List<string> x = new List<string> { "", "", "" };
SomeMethodWitHRef(ref x[0]);

Upvotes: 4

Related Questions