yonan2236
yonan2236

Reputation: 13659

Class variable C#

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?

Upvotes: 5

Views: 1721

Answers (3)

Divi
Divi

Reputation: 7701

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
}

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503379

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.

Upvotes: 8

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60734

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.

Upvotes: 6

Related Questions