1

Yes, I've googled the question but the answers I've found only refer to the old days, before there were getter-only auto-properties.

Today in C# you can declare this:

class Test
{
  readonly int MyField;
  int MyProperty { get; }

  public Test()
  {
    MyField = 42;
    MyProperty = 47;
  }
}

Both declarations can only be initialized either at the line of declaration or in the constructor as seen above.

Is there still a relevant difference between those? Is one to be preferred over the other (e.g. in certain situations, except for interface declaration)?

Dee J. Doena
  • 1,631
  • 3
  • 16
  • 26
  • 2
    One is a property, the other a field. What other "differences" are you looking for? – CodeCaster Nov 22 '17 at 13:14
  • 3
    I think it's duplicate of this question: https://stackoverflow.com/q/3917796/5311735 – Evk Nov 22 '17 at 13:15
  • @Evk Practically yes – EpicKip Nov 22 '17 at 13:16
  • While these two indeed can be assigned in similar way, still usual differences between fields and properties apply: a property can be virtual, can be a part of an interface, etc. – Maciek Nov 22 '17 at 13:17
  • @CodeCaster But in the beginning of properties they were actual implementations of code. With the advent of auto-implementation and especially only-getter auto-implementation it becomes a lot murkier. Hence the question. – Dee J. Doena Nov 22 '17 at 13:19
  • _"Hence the question"_ - **what** question? Which to choose? The property one, for all reasons mentioned in the duplicates. You can replace a property with an alternative implementation and not break binary compatibility (i.e. consumers don't have to recompile). – CodeCaster Nov 22 '17 at 13:20
  • @Evk Back then there was no auto-implementation thus you needed a backing field which could be accessed outside the property. Back then they actually were two different things. Nowadays? Not so much. – Dee J. Doena Nov 22 '17 at 13:21
  • 1
    @DeeJ.Doena you can check in ILSpy or a similar program. I just pasted your code and inspected it with ILSpy both generate a.field private initonly int32 field but one generates the property methods to access it. – Gilles Nov 22 '17 at 13:21
  • 1
    @DeeJ.Doena readonly property compiles to readonly field and property with getter that returns it. So basically the same situation as in question I mentioned above. – Evk Nov 22 '17 at 13:24
  • Thanks @Gilles Unfortunately I'm not good at reading assembler or IL code. But your reply answers my question. :) – Dee J. Doena Nov 22 '17 at 13:24
  • @Evk Now that I've understood what actually happens in IL, I see your point regarding your linked duplicate. Thanks :) – Dee J. Doena Nov 22 '17 at 13:27

0 Answers0