0

What is the difference between {get;} and Readonly in the following C# code?

String name { get { return "Tom"; } }
const String name = "Tom";
readonly String name = "Tom";

please explain with simple problem or any reference.

cja
  • 9,512
  • 21
  • 75
  • 129
v11
  • 2,124
  • 7
  • 26
  • 54
  • 4
    You have already read [this](http://stackoverflow.com/questions/55984/what-is-the-difference-between-const-and-readonly) and [this](http://stackoverflow.com/questions/2719699/when-should-use-readonly-and-get-only-properties)? – Tim Schmelter Jul 13 '16 at 07:38
  • 2
    @KevinWallis: Different people have different conventions for that. It makes no difference whatsoever (assuming there's no conflict). – Jon Skeet Jul 13 '16 at 07:39
  • 1
    Do you understand that the first of these is a property and the other two are fields? – Jon Skeet Jul 13 '16 at 07:39
  • @JonSkeet I read many books about coding (maybe not as much as you :D) and many of them said that in C# `string` should be used for declaration and `String` for calling `String` functions only for readability reasons. But as you said: "Different people have different conventions for that" – wake-0 Jul 13 '16 at 07:42
  • You can't change readonly fields (or constants) after initializartion(so only inline or via constructor). You can change properties without setters from within this class if there is a backing field, otherwise the behaviour is similar to a readonly field. But they are different anyway, one is a field and the other a property. – Tim Schmelter Jul 13 '16 at 07:43
  • 1
    @KevinWallis: Well I use `string` universally, and Jeffrey Richter (CLR via C#) uses `String` universally. Personally I'd prefer a convention which was consistent over one which uses different names for the same type in different places. (How does that make anything more readable?) But I certainly don't think there's any good reason to ask others on SO to use one form or the other - it's not like the well-established conventions around property names (so `name` should be `Name` in the first line in this question). – Jon Skeet Jul 13 '16 at 07:43
  • @JonSkeet okay good point, I deleted my comment – wake-0 Jul 13 '16 at 07:45
  • @JonSkeet when we talk about the first line, does it compile? Because `;` is missing – wake-0 Jul 13 '16 at 07:48
  • @KevinWallis: True. Will fix that myself, as it's clearly a typo. – Jon Skeet Jul 13 '16 at 07:48
  • @JonSkeet Thanks for reminder, I have read [this](http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c) to know the difference between a field and a property. – v11 Jul 13 '16 at 08:04

0 Answers0