Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class variable C#

Tags:

c#

.net

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?

like image 847
yonan2236 Avatar asked Mar 11 '11 07:03

yonan2236


People also ask

What is the class of a variable?

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.

What is a class variable C#?

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.

What is a class variable used for?

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.

How do you declare a class 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.


2 Answers

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.

like image 79
Jon Skeet Avatar answered Oct 08 '22 14:10

Jon Skeet


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.

like image 6
Øyvind Bråthen Avatar answered Oct 08 '22 15:10

Øyvind Bråthen