简体   繁体   中英

How to declare a variable that can be used by every method? | C#

I want to ask you how to declare a variable that can be used by every method?

I tried making the method's access type public but that didn't let me used its variable across other methods

Moreover, I basically want to accumulate that variable with different values across different methods that's why I am asking this.

NOTE: I want to avoid making any static classes.

EDIT:

For example, I did

public decimal MiscMethod()  
{
    decimal value1 += 23m;  
}  

public decimal AutoMethod()  
{
    decimal value 1 += 34;
}

do you mean somethinge like this ?

class Program
{
    static void Main(string[] args)
    {
        var myClass = new MyClass();
        myClass.Print(); //Output: Hello
        myClass.SetVariable();
        myClass.Print(); //Output: Test

    }
}

class MyClass
{
    string MyGlobaleVariable = "Hello"; //my global variable


    public void SetVariable()
    {
        MyGlobaleVariable = "Test";
    }

    public void Print()
    {
        Console.WriteLine(MyGlobaleVariable);
    }
}

with your example:

decimal value1 = 0;

public decimal MiscMethod()  
{
    value1 += 23m;  
}  

public decimal AutoMethod()  
{
    value1 += 34;
}

Use it like a global variable,but make sure after using it in every method you need to nullify the value,as that will not make the value contradictory to other methods.

decimal value1;

public decimal MiscMethod()  
{
    value1 += 23m; 
    //Complete your code using value1
    value1 = 0;
}  

public decimal AutoMethod()
{
    value 1 += 34;
    //Complete your code using value1
    value1 = 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM