Hi
I have two webforms. In the first, i put a public field x, but it's unknown in the second webform, despite the fact is public (i know that session and viewstate allow to pass from one webform to another but that's not the point here) and my question is: apparently, the scope of x is limited to its webform, despite the fact it's public. Why? And what's then the difference between internal and public here?
Thanks
public partial class WebForm1 : System.Web.UI.Page
{
public int x = 5;
protected void Page_Load(object sender, EventArgs e)
{
.......
}
}
Diptiranjan SutarPosted Feb 15, 2023, 5:44 AM
Hello Valerie Meunier,
The scope of the
public int xvariable you have defined in theWebForm1class is limited to the instance of that class. When you create an instance of theWebForm1class (i.e., when you load the web form in a web browser), thexvariable will be initialized to 5 and will be accessible within the code of that instance of theWebForm1class.However, if you create a different instance of a different class (e.g.,
WebForm2) and try to access thexvariable, it will not be available because it belongs to theWebForm1class. In other words, the scope ofxis limited to the instance of theWebForm1class that contains it.The
publicaccess modifier means that thexvariable is accessible from any code that has access to an instance of theWebForm1class. It doesn't mean that the variable is accessible from any code in your entire application. Theinternalaccess modifier, on the other hand, limits the accessibility of the variable to the same assembly (i.e., project) in which it is defined.In summary, the
publicaccess modifier allows you to access thexvariable from any code that has access to an instance of theWebForm1class, but its scope is still limited to the instance of theWebForm1class that contains it.Thanks
Dipti
Valerie MeunierPosted Feb 14, 2023, 10:03 AM
Thanks
Naimish MakwanaPosted Feb 14, 2023, 9:56 AM
Hello Valerie,
In ASP.NET, each web form is a separate class, and the scope of a public field is limited to the class in which it is defined.(It is beacuse Every time you page is postback or refresh (click also refreshes page) new instance of Page class is created. This means that all your fields become empty.)
The difference between internal and public in this context is the accessibility of the field. A public field can be accessed from any class, while an internal field can only be accessed within the same assembly.
Thanks
Naimish Makwana