Home > Backend Development > C#.Net Tutorial > Scope of variables in C#

Scope of variables in C#

王林
Release: 2023-09-19 15:37:02
forward
845 people have browsed it

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();
      }
   }
}
Copy after login

Output

Division Result = 15
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template