Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c# - How to declare global variables?

I have a doubt regarding Memory Management in Variables declaration.

In my class i have around 20 methods, i am using around 50 variables through out my class.

I declared all variables globally at the starting of a class.

Is it the right way of doing? or else which one is better... Using structure or any thing else???

Below am showing a basic example, i need to use optimize my memory.

  class Program
    {
        static  int a, b, c, d;           //----> Here am declaring , i need any other way
        static void Main(string[] args)
        {
            a = 10;
            b = 20;
            c = 30;
            d = 40;

            int result = add(a, b, c, d);
            Console.WriteLine(result);
            Console.ReadLine();
        }
        public static int add(int w, int x, int y, int z)
        {
            return w + x + y + z;
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your class-level variables are only used within a single method, so declare them only within the scope of that method:

static void Main(string[] args)
{
    var a = 10;
    var b = 20;
    var c = 30;
    var d = 40;

    int result = add(a, b, c, d);
    Console.WriteLine(result);
    Console.ReadLine();
}

As a rule of thumb, keep your variables as close to their use as possible. Any time the scope has to increase, step back and think about the structure. Don't just blindly move the variables up in scope.

Is there a reason you're trying to optimize the resource consumption of your code? Chances are, especially in a case this simple, the compiler is doing a fine job of this already. Unless you're seeing actual problems, don't prematurely optimize. More often than not this results in unmanageable code.

Also, and this is a side note because I understand that this is a contrived example... Meaningful variable names are very important. Meaningful names also help you understand and identify the desired scope of your variables. If a variable is called a then that doesn't give you any context about what it means. But if the name tells you what it means then you can more readily visualize what context in the code is actually responsible for that value, resulting in better scope definition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...