Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property with private setter versus get-only-property

Tags:

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?

like image 784
SeToY Avatar asked Aug 10 '15 20:08

SeToY


People also ask

What is a getter only property?

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.

What does get private set mean?

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.

What does get private set mean in C#?

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.

Should properties be private C#?

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.


1 Answers

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.

like image 184
Paulo Morgado Avatar answered Sep 17 '22 16:09

Paulo Morgado