-1

I have a simple inheritance situation as follows:

I expected to be able to set the properties in Class2 from Class1 but this is not the case. Is there a way to set access to the properties in Class 2 so they act like protected variables?

public abstract class Class2
{
    public DateTime Added { get; private set; }
    public int ID { get; private set; }
}

public class Class1 : Class2
{
    public string ImageFilename { get; set; }
    public string LinkText { get; set; }
}
dotnetnoob
  • 10,783
  • 20
  • 57
  • 103
  • 5
    Have you tried making the set protected? – Kik Jan 23 '15 at 16:13
  • 1
    [protected](https://msdn.microsoft.com/en-us/library/bcd5672a.aspx) – crashmstr Jan 23 '15 at 16:13
  • Please define _"act like protected variables"_, as that can mean a lot. Do you want the properties to not be accessible from outside `Class2` and its inheritance chain? Do you want the property to be publicly gettable, but protected settable? And so on. And please share your research. – CodeCaster Jan 23 '15 at 16:15
  • 3
    `"so they act like protected variables"` - I don't understand... If you know what `protected` is, why aren't you using it? Is there more to this problem that you're not explaining? – David Jan 23 '15 at 16:17

1 Answers1

4

You need to set them as protected, not private. This lets you access it from derived classes, but not external classes.

public abstract class Class2
{
    protected DateTime Added { get; set; }
    protected int ID { get; set; }
}

public class Class1 : Class2
{
    public string ImageFilename { get; set; }
    public string LinkText { get; set; }

    public Class1()
    {
        //You can set the variables from inside Class 1.
        base.Added = DateTime.Now();
        base.ID = 1;
    }
}

If you want the properties to still be exposed externally, but as readonly, you can set the individual setters are protected instead:

public abstract class Class2
{
    public DateTime Added { get; protected set; }
    public int ID { get; protected set; }
}
Obsidian Phoenix
  • 4,083
  • 1
  • 22
  • 60