1

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.

Mr. Smith
  • 4,288
  • 7
  • 40
  • 82

1 Answers1

4

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]);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Just to be absolutely certain I'm reading this right, does that imply my indexer is returning a *copy* of the struct `T`? – Mr. Smith Jan 04 '14 at 10:58
  • 2
    @Mr.Smith: Yes, in exactly the same way as a simple assignment would copy the value. – Jon Skeet Jan 04 '14 at 11:01