views:

609

answers:

2

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?

+2  A: 

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; }
}
najmeddine
I tested this, and it actually doesn't work at all. The "Password" property from the base class is still visible in the other assembly.
Nader Shirazie
When you inherit from a base you are creating a new class, you are not modifying the behavior of the base class. Of course, the 'Password' property of UserInfo is still visible outside the assembly but ReadUserInfo.Password is not.
najmeddine
@najmeddine: Right, which means if you cast it the right (or wrong way) within the assembly, you'll get either UserInfo.Password, or ReadUserInfo.Password. That's part of the problem with this approach.
Nader Shirazie
Unfortunately this is one of those places where the abstraction model of OOP starts to break down. It's probably best to avoid this situation altogether in order to avoid confusing people who use this class.
Nate C-K
+7  A: 

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

Nader Shirazie
This was half an experimental rewrite, half learning exercise on a personal project. Wasn't quite sure if I was going in the right direction. I was also mistaken on behavior when stored back to the base type. So yeah this was a bad idea. Thanks for the input!
apocalypse9