Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between readonly and { get; }

Do these statements mean the same thing?

int x { get; }
readonly int x;
like image 239
Bob Avatar asked Jul 27 '10 15:07

Bob


People also ask

What is the difference between the readonly?

The difference between disabled and readonly is that read-only controls can still function and are still focusable, whereas disabled controls can not receive focus and are not submitted with the form and generally do not function as controls until they are enabled.

Is readonly same as final?

In Java, final means a variable can only be assigned to once, but that assignment can happen anywhere in the program. In C#, readonly means a field can only be assigned in a constructor, which, IMO, is significantly less useful.

What is a readonly?

Read-only is a file attribute which only allows a user to view a file, restricting any writing to the file. Setting a file to “read-only” will still allow that file to be opened and read; however, changes such as deletions, overwrites, edits or name changes cannot be made.

What is the use of readonly?

The readonly keyword can be used to define a variable or an object as readable only. This means that the variable or object can be assigned a value at the class scope or in a constructor only. You cannot change the value or reassign a value to a readonly variable or object in any other method except the constructor.


2 Answers

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.

like image 84
John Warlow Avatar answered Sep 24 '22 20:09

John Warlow


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).

like image 29
Johannes Rudolph Avatar answered Sep 24 '22 20:09

Johannes Rudolph