C# 6.0 introduces the ability to define get-only properties:
public ICommand AddCommand { get; }
Now when defining another property like the following, ReSharper suggests Auto-property can be made get-only:
private List<Screenshot> Screenshots { get; set; }
Futhermore, ReSharper doesn't say a thing when defining private getters:
public ICommand AddCommand { get; private set; }
What's the difference between a public get-only property (such as the first AddCommand
), a private get-only property (such as the Screenshots
property) and the public private setter property (such as the second AddCommand
)?
My WPF application doesn't seem to care whether its public property (UICommand) contains a private setter or no setter at all, but surely there must be a difference?
The JavaScript strict mode-only exception "setting getter-only property" occurs when there is an attempt to set a new value to a property for which only a getter is specified.
Private setter means the variable can be set inside the class in which it is declared in. It will behave like readonly property outside that class's scope. Read only property can only be accessed, not mutated. No exception.
Since it is a read operation on a field, a getter must always return the result. A public getter means that the property is readable by everyone. While the private getter implies that the property can only be read by class and hence is a write-only property.
Generally, you should declare your fields as private, then use Properties to get and set their values. By this way you won't affect their values them directly. This is common case practice since having public members violates the Encapsulation concept in OOP.
Short answer:
public ICommand AddCommand { get; }
will be backed by a readonly
field and no C# code will be able to change it beyond the execution of the constructors.
Also, the compiler will generate code to directly assign the backing filed, as there is no property accessor.
On the other hand:
public ICommand AddCommand { get; private set; }
will be backed by a non-readonly
field and can be assigned at any time by any code with access to private members.
In this case, the compiler will generate normal property setting code.
To the outside world, a private setter is as if it doesn't exist. So, it's the same as if it didn't really exist.
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