Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to C# and trying to use a global variable

Tags:

c#

asp.net

Is it possible to use global variables in C#? I'm coming from mainly a PHP background so variables are either accessible everywhere or just a global definition away.

My main issue is I have a User class that I built myself to wrap around the current users table on my company's database. I am defining it in the MasterPage but can't seem to access it from the actual pages (I don't know if there's a better word to describe them but they are the pages that inherit the styles and format from the MasterPage)

Any general tips or implementation practices for me?

EDIT: here's some code snippets of what I'm trying to do:

Site.master.cs

public partial class SiteMaster : System.Web.UI.MasterPage
{
    public User user = new User();
}

logout.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="logout.aspx.cs" Inherits="logout" %>
<%@ MasterType  virtualPath="~/Site.master"%>

logout.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        User user = Master.user;
    }
}
like image 446
Andrew G. Johnson Avatar asked Jan 27 '26 20:01

Andrew G. Johnson


1 Answers

No, it is impossible. It is possible to create singletons or public static classes, but this is bad practice.

C# was designed for object oriented programming. If you haven't written programs using object oriented paradigm before it can be a bit hard to switch to it in the beginning. OOP (http://en.wikipedia.org/wiki/Object-oriented_programming) is built on three main concepts: inheritance, polymorphism and encapsulation.

You can defined classed apart of the pages/masterpages, it is good practice to define them in the App_Code folder.

like image 69
Andrew Bezzub Avatar answered Jan 29 '26 08:01

Andrew Bezzub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!