Scope of Variables in C#


The scope of a variable is a region of code that indicates where the variables are being accessed.

For a variable, it has the following levels −

Method Level

Variable declared inside a method is a local variable.

Class Level

Variable declared inside a class is a local variable are class member variables.

Let us see an example of scope of variables −

Example

 Live Demo

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

598 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements