Home > Software engineering >  c# variable access from many different classes
c# variable access from many different classes

Time:02-03

What is the common way to access a variable in c#, that is used by many different functions and classes? Should you just pass this variable to every class/function that needs it or should you better create a new instance of the class, that holds the variable and access it inside the class/function that needs to call the variable?

CodePudding user response:

It depends on on type of project and files hierarchy

One way is to create one Base class and inherit from it to every class your using

class BaseController
{
    string connectionString = "..." //this is your often used variable
}

class UsersController : BaseController
{
    Connect(connectionString);

    //rest of class
}

class GroupsController : BaseController
{
    Connect(connectionString);

    //rest of class
}

Another way is to create class with static varibles if you can and call them without class instance

class MyVariables
{
    static string connectionString = "..." //this is your often used variable
}

And call it like this

Connect(MyVariables.connectionString);

I think The second option is better

  •  Tags:  
  • c#
  • Related