Search code examples
c#.netglobal-variables

How to change variable from one class using another in C#


The title may sound a bit confuse, but what I want to do is basicaly create a class, declare a public int with the default value of 0, then inside the Program class I permanently change the value of this variable in a function, and if I print this value using another function, it will print the value set in the first function. For example:

using System;
{

    class Global
    {
       public int variable = 0;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Global test = new Global();
            test.variable = 10;
            //it makes no sense in this code to use another function, 
            //but in my other project it does
            Function();
            Console.ReadLine();
        }
        
        static void Function()
        {
            Global test = new Global();
            //should print 10
            Console.WriteLine(test.variable);
        }
        
    }
    
}

Solution

  • You could create a static class if you don't want to bother with injection like this:

    public static class Global
    {
        public int variable = 0;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Global.variable = 10;
        }
        static void Function()
        {
            Console.WriteLine(Global.variable);
        }
    }
    

    or you could just inject the class through as a parameter from wherever you call it.

    public class Global
    {
        public int variable = 0;
    }
    class Program
    {
        static void Main(string[] args)
        {
            var test = new Global();
            test.variable = 10;
        }
        static void Function(Global global)
        {
            Console.WriteLine(global.variable);
        }
    }
    

    If you want to permanently change this variable inside every class you could use a static class, but then you wouldn't be able to create instances of it (if you wanted other variables to be non-static.

    I would recommend looking into IServiceProviders because they can be really useful if the Function() method is inside another class and you want to pass through the Global class.