What are the member variables of a class in C#?

CsharpProgrammingServer Side Programming

A class is a blueprint that has member variables and functions in C#. This describes the behavior of an object.

Let us see the syntax of a class to learn what are member variables −

<access specifier> class class_name {
   // member variables
   <access specifier> <data type> variable1;
   <access specifier> <data type> variable2;
   ...
   <access specifier> <data type> variableN;
   // member methods
   <access specifier> <return type> method1(parameter_list) {
      // method body
   }
   <access specifier> <return type> method2(parameter_list) {
      // method body
   }
   ...
   <access specifier> <return type> methodN(parameter_list) {
      // method body
   }
}

Member variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.

Below length and width are member variables because a new instance/ of this variable will get created for each new instance of Rectangle class.

Example

 Live Demo

using System;

namespace RectangleApplication {
   class Rectangle {
      //member variables
      private double length;
      private double width;

      public void Acceptdetails() {
         length = 10;
         width = 14;
      }

      public double GetArea() {
         return length * width;
      }

      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }

   } //end class Rectangle

   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine();
      }
   }
}

Output

Length: 10
Width: 14
Area: 140
raja
Published on 06-Aug-2018 16:24:10
Advertisements