Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it means? [c#]

If we define a property as public property and in this property we have a protected getter. what does it means? if property is public, what does defining a protected getter for that, means? please see below code:

    public ISessionFactory SessionFactory
    {
        protected get { return sessionFactory; }
        set { sessionFactory = value; }
    }
like image 397
masoud ramezani Avatar asked Dec 12 '22 22:12

masoud ramezani


2 Answers

It means, that the getter can only be called by subclasses. The 'protected' before the getter so to say overwrites the 'public' for the getter part of the property.

like image 162
Danvil Avatar answered Dec 15 '22 14:12

Danvil


In C# you are allowed to have getters and setters with access levels (see access modifiers) different than the overall property. This is the most common pattern

public class FooObject
{
    public String Foo 
    {
      get;
      private set;
    }
}

This allows objects instantiating FooObject to retrieve the value of Foo but not set it's value. The private modifier on the setter signifies that only FooObject itself has this ability (not including the use of reflection).

There are two advantages to this:

  1. With the addition of automatic properties (no variables needed assign the get and set value), this allows the private setting of the property variable (it's created for you at compile time), to be done so without having to explicitly create the variable. Without this you couldn't use an automatic property, unless you always wanted the get and set function to be all public, all private etc.

  2. It allows a level of abstraction, so that all methods whether public, private, or otherwise to go through the property and not directly access the private variable. See this question for more information.

In your instance other objects may set the session factory value, but only classes which inherit from it may retrieve it. Most of the time, if an object can set the value, it can also retrieve it, but there are instances where it would beneficial to not allow it. This is allowed, because the set event does not allow a greater amount of access than what was defined for the overall property.

The best example I can think of would be if on the set event, the set object was modified. For example, if it the set event was setting a connection object, and on the setting event, the connection string was added and the connection to the database was opened (In my example, I would probably refactor the code not to act in this way, but something like that could arise).

like image 32
kemiller2002 Avatar answered Dec 15 '22 13:12

kemiller2002