Search code examples
c#inheritancepropertieshierarchyaccess-modifiers

Different Derived Class' Access Modifiers from a Single Base Class


I would not like to write the same code until it's necessary.

There should be a base class (interface doesn't suit, i suppose)

public class MyUser
{
    public string Username
    {
        get;
        set;
    }
    //...many other fields
}

In one of derived classes, PRIVATE set modifiers (aka Only for this Class' methods) are required.

public class MyPrivateInfo : MyUser//, IMyUser
{
    public string Username
    {
        get;
        private set;
    }
}

In the other class, INTERNAL modifiers (aka Library-Wide scope) are required.

public class MyLibInfo : MyUser//, IMyUser
{
    public string Username
    {
        get;
        internal set;
    }
    //...many other fields
}

I suppose there's the way to make a field of type MyUser, that's however not the aim. Fields should be directly accessible in each class.

What's the best way to accomplish this or there is not one?


Solution

  • First off, you can use an interface for this. You just need to not specify a set method.

    This will allow you to define whatever accessibility for a set that you want.

    public interface IUser
    {
        string Username { get; }
    }
    
    public class MyPrivateInfo : IUser
    {
        public string Username
        {
            get;
            private set;
        }
    }
    
    public class MyLibInfo : IUser
    {
        public string Username
        {
            get;
            internal set;
        }
    }