Where can I use the public variable?

Asked 2 years ago, Updated 2 years ago, 126 views

The development environment is vb.net. Where can I use the public variable?

vb.net

2022-09-30 17:36

2 Answers

I don't do vb.net, but I think it's almost the same as C#, so I'll answer with C#.
Use the public variable if you want to access it from another class.
It is usually suggested that you do not use the public variable, but use the private variable to access it through the set, get method.
However, if you decide that you don't need to prepare the set and get methods one by one in a small test program, you can use the public variable.
Do you understand now?


2022-09-30 17:36

The public variable can be declared as a variable placed outside the procedure.
Include the public keyword in variables that you want to read and write from other modules and classes.
For more information, see How: Control Variable Availability (Visual Basic) .

In short, public variables are accessible from the outside, but private variables are restricted.
Then, don't you think it would be more convenient to set all variables to public?

However, most programming textbooks say, "You should use private and friends as much as possible to prevent unnecessary access to variables."
The above is referred to as "scoping out variables."

For example, suppose that the value of the variable i used when you want to For loop inside a procedure is incorrect.
At this time, if the variable i is private, you only need to look at where i is used in the procedure, but if it is public, you don't know where it is being rewritten, so you have to find out where i is used throughout the application.
If the error is caused by a reset of i if the variable i is being used repeatedly in procedures A and B and the process of looping B begins while A is looping, it may be difficult to reproduce or correct the error.

As for where and when to use public variables, you will be asked to use them properly in places where they should be shared by multiple modules.

As others have said, it is desirable to use the Property procedure (Visual Basic) as the next step to understand public/private.
Properties allow fine-grained control, such as allowing references only from other modules and limiting the range of rewritten values.


2022-09-30 17:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.