Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict access of a nested class's Property setter to the outer class only?

Tags:

c#

Is there an access modifier, or combination thereof, to restrict access to an outer class only?

For the Position property of nested class PanelFragment below, I would like only the containing class ViewPagerPanels to be able to set it (via the setter, I realize this could be done through a constructor parameter also).

public class ParcelView : MXActivityView<ParcelVM>, ViewPager.IOnPageChangeListener, IFragmentToViewPagerEvent
{
    private ViewPagerPanels _pagerPanels;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        _pagerPanels = new ViewPagerPanels(5);  // 5: magic number, put int constant

        _pagerPanels[0] = new ViewPagerPanels.PanelFragment(typeof(ViewA));
        // ...
    }

    private class ViewPagerPanels
    {
        public class PanelFragment
        {
            public Fragment Fragment { get; set; }
            // ?? - access modifer for set
            public int Position { get; private set; }
        }

        public readonly int PANEL_COUNT;

        private PanelFragment[] _panels;

        public ViewPagerPanels(int count)
        {
            PANEL_COUNT = count;
            _panels = new PanelFragment[PANEL_COUNT];
        }

        public PanelFragment this[int i]
        {
            get
            {
                return _panels[i];
            }

            set
            {
                _panels[i] = value;
                // !! - cannot access private property
                _panels[i].Position = i;
            }
        }
    }
}
like image 858
samus Avatar asked Oct 20 '25 10:10

samus


1 Answers

No, it's not possible to do it directly. The most restrictive access modifier, private, already allows access from within the same class. Every other modifier further expands that access.

Every class, no matter if its nested, private or public, always has access to every single of its own declared members, with no chance of applyng restrictions to itself. The closest we can get is by using a readonly field (or a getter only property) that prevents the declaring class from modifying a variable outside the constructor. But for a read-write one, we're out of options.

like image 56
Alejandro Avatar answered Oct 21 '25 22:10

Alejandro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!