1

I have a struct:

struct S {
    public readonly int Value1;
    public readonly int Value2;
    public S(int value1, int value2) {
        this.Value1 = value1;
        this.Value2 = value2;
    }
}

and I try to take the address of Value2:

var s = default(S);
unsafe {
    var r = new IntPtr(&s.Value2);
}

but I get a compiler error:

Cannot take the address of the given expression

I thought I could take the addresses of fields? What's going on?

Craig Gidney
  • 17,763
  • 5
  • 68
  • 136
  • http://stackoverflow.com/questions/5079736/cannot-take-the-address-of-the-given-expressionc-pointer –  Jul 08 '13 at 03:33
  • That's a similar question, but resolution is entirely different. The issue was syntactic, not semantic. Plus the only mention of `readonly` is a slightly-wrong answer which appears to be talking about the result-is-a-copy-ness rather than the readonly-ness. – Craig Gidney Jul 08 '13 at 04:08

1 Answers1

3

Apparently it doesn't work with readonly fields. Changing S to this:

struct S {
    public int Value1;
    public int Value2;
}

fixes the problem.

Craig Gidney
  • 17,763
  • 5
  • 68
  • 136