Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static automatic properties is only useful in which the getter is public and setter is private

In book <<c# in depth>>, I have read a sentence "The only scenario in which I can see static automatic properties being useful is where the getter is public and setter is private, and the setter is only called whithin the type initializer". I am not sure what's Jon skeet suggested here.

In my opinion both getter and setter can be used as private or public.

like image 340
ValidfroM Avatar asked Mar 24 '23 20:03

ValidfroM


1 Answers

The point is that static members should generally be thread-safe... and automatically-implemented properties aren't thread-safe, in terms of any guarantee that a value written by one thread will be immediately visible to another. You can't change that within an automatic property, so the only times a static automatic property are useful are:

  • If you don't care about thread safety
  • If the setter is private and only set from the static initializer (which is thread-safe automatically). In this case I'd usually just have a readonly static variable and a getter-only property to expose it anyway.

To be honest, settable static properties are pretty unusual (in well-designed code) to start with, even without the thread safety aspect.

like image 75
Jon Skeet Avatar answered Apr 06 '23 10:04

Jon Skeet