nosirrahx
nosirrahx

Reputation: 31

C# novice question about modifying outside variables inside a method

In the examples below I want to know a good way to make the bottom example function like the top example. I know that scope is the reason the bottom example does not work.

I am interested in doing this so I can tidy up the main body of my programs and eliminate some duplicated code.

namespace example_1
{
    class Program
    {
        static void Main(string[] args)
        {
            int test = 5;
            bool trigger = true;
            if (trigger)
            {
                test++;
                trigger = false;
            }
        }
    }
}
namespace example_2
{
    class Program
    {
        static void Main(string[] args)
        {
            int test = 5;
            bool trigger = true;
            if (trigger)
            {
                mod_test();
            }
        }
        public static void mod_test()
        {
            test++;
            trigger = false;
        }
    }

Upvotes: 2

Views: 99

Answers (2)

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

I think using a data container object is more suitable in this case. For example, in the following example, I wrapped the int and bool variables into a TestDataclass. This way you don't have to use global variables and still pass around the object reference for any kind of manipulation.

namespace example_3
{
    class TestData
    {
        public bool Trigger { get; set; }
        public int Test { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var testData = new TestData
            {
                Test = 5,
                Trigger = true
            };

            if (testData.Trigger)
            {
                mod_test(testData);
            }
        }

        public static void mod_test(TestData data)
        {
            data.Test++;
            data.Trigger = false;
        }
    }
}

Upvotes: 0

Cid
Cid

Reputation: 15247

You can declare the properties outside of the methods, but still in the class :

class Program
{
    // both of them are accessible within the class scope, but not outside
    static int test = 5;
    static bool trigger = true;

    static void Main(string[] args)
    {
        if (trigger)
        {
            mod_test();
        }
    }

    public static void mod_test()
    {
        test++;
        trigger = false;
    }
}

Upvotes: 3

Related Questions