Tutorial :Is there a difference between readonly and { get; }



Question:

Do these statements mean the same thing?

int x { get; }  readonly int x;  


Solution:1

In answer to your question: There is a difference between readonly and {get; }:

In int x { get; } (which won't compile as there's no way to set x - I think you needed public int x { get; private set; } ) your code can keep changing x

In readonly int x;, x is initialised either in a constructor or inline and then can never change.


Solution:2

readonly int x; declares a readonly field on a class. This field can only be assigned in a constructor and it's value can't change for the lifetime of the class.

int x { get; } declares a readonly auto-implemented property and is, in this form, invalid (because you'd have no way whatsoever to set the value). A normal readonly property does not guarantee to return the same value every time it is called. The value can change throughout the lifetime of the class. For example:

public int RandomNumber  {      get { return new Random().Next(100); }  }  

This will return a different number everytime you call it. (Yes, this is a terrible abuse of properties).


Solution:3

No, the statements do not mean the same thing. The full version of the property will have a backing variable:

private int _x;    public int X  {      get { return _x; }  }  

Another method in the class could modify the backing variable, changing the value of the property:

private void SomeMethod(int someValue)  {      _x = someValue * 5;  }  

The readonly keyword only allows a member variable to be assigned in its declaration or in the constructor:

// Both of these compile    private readonly int _x = 1;    public SomeClass()  {      _x = 5;  }    // This will not compile    private void SomeMethod(int someValue)  {      _x = someValue * 5;  }  

So a get-only property whose backing variable is marked readonly is a true read-only property.


Solution:4

Literally, there's no big difference because you've declared x to be private (the default). You can always re-compile your class to make x different.

However, if it were public, the definition public int x { get; } allows you to later expand the definition to something like this:

int x { get {       return DoSomeOperation();      }  }  

You can do that without breaking your clients. The implementation of the getter is private and clients call it without knowing if it is a static value or has an operation inside its get accessor.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »