5

Suppose I have 3 classes namely: Class1, Class2 and class3. Class3 has a variable var3.

Is it possible that var3 (from Class3) can only be accessed by Class1 and not by Class2 or any other classes?

3 Answers 3

8

Another option in addition to the ones mentioned:

public class Class3
{
    private int var3;

    public class Class1
    {
        public void ShowVar3(Class3 instance)
        {
            Console.WriteLine(instance.var3);
        }
    }
}

Which option is the right one will depend on your context. I'd argue that whatever you do, you almost certainly shouldn't be trying to access another class's variables directly - but all of this applies to members as well, which is more appropriate.

Sign up to request clarification or add additional context in comments.

1 Comment

@yonan2236: Right, although exactly the same principles will apply.
6

Put Class1 and Class3 in the same assembly, and make Class3 internal. Then it will only be visible to the other classes inside the same assembly.

2 Comments

This is likely the right answer to the OP's question, +1 for that. But perhaps the OP should reconsider their approach using inheritance or interfaces instead of a non-OOP way of 'rights management'.
@Bazzz - I totally agree with you here. There is something a bit awkward in the OP's architecture.
3

If you make var3 protected for class3 and make class1 inherit from class3 it'll work

Edited, when its a property

Eg:

public class Class3
{
     protected int Var3 {get;set;}
}


public class Class2
{
}


public class Class1 : Class3
{
   //access Var3 here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.