Do these statements mean the same thing?
int x { get; }
readonly int x;
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.
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With