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

StackOverflow https://stackoverflow.com/questions/16730912

  •  30-05-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution 2

Because auto-properties break encapsulation, which is a basic priciple of OOP. You cannot encapsulate data with auto-properties. The job of encapsulation is to ensure, that your object stays in a consistent state. If you are using auto-properties like this:

public IFoo Foo { get; set; }

you have no option to validate the value in the setter. Setting the property to null is possible without giving you any chance to even notice or forbid it. This may be what you want, but it probably makes it easier to use your interface wrong. This is why the previously mentioned blog-post states

It's a code smell, not an anti-pattern.

You should prefer this style:

public IFoo Foo { get; private set; } 

because then you're given the possibility to inject your reference together with the constructor.

public Bar(IFoo foo)
{
    if (foo == null) 
        throw new ArgumentNullException("Foo");

    this.Foo = foo;
}

This makes it easier for clients to use your object the right way. I really suggest reading the previously mentioned blog-post. It describes very well why you should prefer keeping the setter private.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top