Question

I have the following class hierarchy

 public class Third : Second
{
}

public class Second : First
{
}

public class First
{
     private int MyVariable;
}

if i want to access MyVariable from Second and Third, I could make MyVariable protected but what if i want to access from Second but NOT Third. Is that possible?

Was it helpful?

Solution 2

You're not thinking about this in an object-oriented manner.

You state that every Third is a Second. But you want every Second to have access to the variable, but you don't want any Third to have access.

But if Third does not have access, then it is not a Second!

OTHER TIPS

If I want to access MyVariable from Second and Third I could make MyVariable protected. What if I want to access from Second but NOT Third. Is that possible?

Yes! Here's one technique:

class First
{
    private int myVariable;
    public class Second : First
    {
        public Second() { myVariable = 123; } // Legal!
    }
}

class Third : First.Second
{
    public Third() { myVariable = 456; } // Illegal!
}

Here's another:

// Alpha.DLL
public class First 
{ 
    internal int myVariable;
}
public class Second : First
{
    public Second() { myVariable = 123; } // Legal!
}

// Bravo.DLL
class Third : Second
{
    public Third() { myVariable = 456; } // Illegal!
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top