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?
Class Variable: It is basically a static variable that can be declared anywhere at class level with static. Across different objects, these variables can have only one value. These variables are not tied to any particular object of the class, therefore, can share across all objects of the class.
Static variables are also known as Class variables. If a variable is explicitly declared with the static modifier or if a variable is declared under any static block then these variables are known as static variables.
A class variable is an important part of object-oriented programming (OOP) that defines a specific attribute or property for a class and may be referred to as a member variable or static member variable.
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With