Home  >  Article  >  Backend Development  >  Scope of variables in C#

Scope of variables in C#

王林
王林forward
2023-09-19 15:37:02806browse

C# 中变量的作用域

The scope of a variable refers to the code area where the variable is accessed.

For a variable, it has the following levels:

Method level

Variables declared within a method are local variables.

Class level

Variables declared within a class are local variables and class member variables.

Let’s look at an example of variable scope:

Example

Real-time demonstration

using System;

namespace Demo {
   class Program {
      public int Divide(int num1, int num2) {
         // local variable in a method
         int result;
         result = num1 / num2;
         return result;
      }
      static void Main(string[] args) {
         // local variable
         int a = 150;
         int b = 10;
         int res;
         Program p = new Program();
         res = p.Divide(a, b);
         Console.WriteLine("Division Result = {0}", res );
         Console.ReadLine();
      }
   }
}

Output

Division Result = 15

The above is the detailed content of Scope of variables in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete