Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Access Modifiers with Inheritance

I'd like to have multiple versions of an object with different access modifiers on the properties

For example I might have a user class-

public abstract class UserInfo
{
    internal UserInfo()
    {
    }
    public virtual int ID { get; set; }
    public virtual string Password { internal get; set; }
    public virtual string Username { get; set; }
}

public class ReadUserInfo : UserInfo 
{
    internal ReadUserInfo()
    {
    }
    override public int ID { get; internal set; }
    override internal string Password { get; set; }
    override public string Username { get; internal set; }
}

public class NewUserInfo : UserInfo
{
    internal NewUserInfo()
    {
        ID = -1;
    }
     //You get the Idea
}

Is this something I can implement or do I have to control access in a more programmatic fashion?

like image 826
Kelly Robins Avatar asked Dec 03 '22 07:12

Kelly Robins


2 Answers

Is inheritance really the right fit here? Users of the UserInfo class shouldn't need to be aware of the subtypes. In this case, users would need to know that the Password property is somehow unavailable when given a ReadUserInfo instance rather than a UserInfo instance.

This really doesn't make sense.

Edit: In OO design, this is known as the Liskov Substitution Principle

like image 86
Nader Shirazie Avatar answered Dec 20 '22 03:12

Nader Shirazie


you can use the new modifier:

public class ReadUserInfo : UserInfo
{
    internal ReadUserInfo()
    {
    }
    new public int ID { get; internal set; }
    new internal string Password { get; set; }
    new public string Username { get; internal set; }
}
like image 28
manji Avatar answered Dec 20 '22 05:12

manji