Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Improving encapsulation of property in this example?

I know of the error "The accessibility modifier of the set accessor must be more restrictive than the property or indexer". I also know the solution. Just not in this very specific case.

Consider this example:

    internal virtual bool IsFocused
    {
        get
        {
            return isFocused;
        }
        protected set
        {
            isFocused = value;
        }
    }
    private bool isFocused;

It shows the error. I just don't know why. How is "protected" not less accessible than internal? What would be the solution to this problem? I tried putting "internal protected" instead, without luck.

like image 214
Mathias Lykkegaard Lorenzen Avatar asked Jul 30 '11 23:07

Mathias Lykkegaard Lorenzen


2 Answers

As it turns out, protected is more accessible than internal. Recall that internal means "not visible outside of this assembly" (except through InternalsVisibleTo access, which makes internal look like public), whereas protected means visible to all subclasses.

like image 197
bobbymcr Avatar answered Sep 30 '22 18:09

bobbymcr


@bobbymcr is entirely right in his analysis. The solution would be to mark property as internal protected. In C# that means that it would be accessible both to derived classes AND to all classes from current assembly.

If you put internal protected to accessor method - that means that it is accessible to derived classes. But entire property is not, which causes the error. If you mark entire property as internal protected and accessor method as protected - everything is fine.

internal protected virtual bool IsFocused
{
    get
    {
        return isFocused;
    }
    protected set
    {
        isFocused = value;
    }
}
private bool isFocused;

Other option would be to introduce protected method that would be called in setter. Then you could mark entire property as internal and allow to override only that method.

like image 38
Ivan Danilov Avatar answered Sep 30 '22 18:09

Ivan Danilov