C # Class


Release date:2023-08-30 Update date:2023-10-13 Editor:admin View counts:329

Label:

C # Class

When you define a class, you define a blueprint for data types. This does not actually define any data, but it defines what the name of the class means, that is, what the object of the class consists of and what actions can be performed on that object. Object is an instance of a class. The methods and variables that make up a class are called members of the class.

Definition of class

Class is defined by keyword class start, followed by the name of the class. The body of the class, contained in a pair of curly braces. The following is the general form of a class definition:

<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
    }
}

Please note:

  • Access identifier <access specifier> specifies access rules for the class and its members. If not specified, the default access identifier is used. The default access identifier for the class is internal access identifier for members is private .

  • Data type <data type> specifies the type of the variable and returns, the type <return type> specifies the data type returned by the returnedmethod.

  • If you want to access members of a class, you need to use the . operator

  • The dot operator links the names of objects and members.

The following examples illustrate the concepts discussed so far:

Example

using System;
namespace BoxApplication
{
    class Box
    {
       public double length;   // length
       public double breadth;  // width
       public double height;   // height
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // statement Box1,type are Box
            Box Box2 = new Box();        // statement Box2,type are Box
            double volume = 0.0;         // volume
            // Box1 explain
            Box1.height = 5.0;
            Box1.length = 6.0;
            Box1.breadth = 7.0;
            // Box2 explain
            Box2.height = 10.0;
            Box2.length = 12.0;
            Box2.breadth = 13.0;

            // Box1's volume
            volume = Box1.height * Box1.length * Box1.breadth;
            Console.WriteLine("Box1's volume: {0}",  volume);
            // Box2's volume
            volume = Box2.height * Box2.length * Box2.breadth;
            Console.WriteLine("Box2's volume: {0}", volume);
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Box1's volume: 210
Box2's volume: 1560

Member functions and encapsulation

A member function of a class is a function that has its definition or prototype in the class definition, just like other variables. As a member ofa class, it can operate on any object of the class and can access all members of that object’s class.

Member variables are properties of the object (from a design perspective), and they remain private for encapsulation. These variables can only be accessed using public member functions.

Let’s use the above concept to set and get the values of different class members in a class:

Example

using System;
namespace BoxApplication
{
    class Box
    {
       private double length;   // length
       private double breadth;  // width
       private double height;   // height
       public void setLength( double len )
       {
            length = len;
       }
       public void setBreadth( double bre )
       {
            breadth = bre;
       }
       public void setHeight( double hei )
       {
            height = hei;
       }
       public double getVolume()
       {
           return length * breadth * height;
       }
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // statement Box1,type is Box
            Box Box2 = new Box();                // statement Box2,type is
Box
            double volume;                               // Volume
            // Box1 explain
            Box1.setLength(6.0);
            Box1.setBreadth(7.0);
            Box1.setHeight(5.0);
            // Box2 explain
            Box2.setLength(12.0);
            Box2.setBreadth(13.0);
            Box2.setHeight(10.0);

            // Box1's volume
            volume = Box1.getVolume();
            Console.WriteLine("Box1's volume: {0}" ,volume);
            // Box2's volume
            volume = Box2.getVolume();
            Console.WriteLine("Box2's volume: {0}", volume);

            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Box1's volume: 210
Box2's volume: 1560

C # constructor

The constructor of a class is a special member function of the class that isexecuted when a new object of the class is created.

The name of the constructor is exactly the same as the name of the class, and it does not have any return type.

The following example illustrates the concept of a constructor:

Example

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // The length of the line
      public Line()
      {
         Console.WriteLine("Object Created");
      }
      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }
      static void Main(string[] args)
      {
         Line line = new Line();
         // Set Line Length
         line.setLength(6.0);
         Console.WriteLine("The length of the line: {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following results:

Object Created
Length of the line: 6

The default constructor does not have any arguments. But if you need a constructor with parameters that can have arguments, this constructor is called a parameterized constructor. This technique can help you assign initial values to objects while creating them. For more information, please see the following example:

Example

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // The length of the line
      public Line(double len)  // Parameterized constructor
      {
         Console.WriteLine("Object Created,length = {0}", len);
         length = len;
      }
      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }
      static void Main(string[] args)
      {
         Line line = new Line(10.0);
         Console.WriteLine("The length of the line: {0}", line.getLength());
         // Set Line Length
         line.setLength(6.0);
         Console.WriteLine("The length of the line: {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following results:

Object Created,length = 10
The length of the line: 10
The length of the line: 6

Destructor in C #

The destructor of a class is a special member function of the class, which is executed when the object of the class is out of scope.

The name of the destructor is prefixed with a wavy (~) in front of the name of the class, which returns no value and no parameters.

Destructors are used to release resources before ending the program (such as closing files, freeing memory, and so on). Destructors cannot be inherited or overloaded.

The following example illustrates the concept of a destructor:

Example

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // The length of the line
      public Line()  // Constructor
      {
         Console.WriteLine("Object Created");
      }
      ~Line() //Destructor function
      {
         Console.WriteLine("Object deleted");
      }
      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }
      static void Main(string[] args)
      {
         Line line = new Line();
         // Set Line Length
         line.setLength(6.0);
         Console.WriteLine("The length of the line: {0}", line.getLength());

      }
   }
}

When the above code is compiled and executed, it produces the following results:

Object Created
Line length: 6
Object deleted

Static members of the C# class

We can use it. static keyword defines class members as static. When we declare a class member static, it means that no matter how many objects of the class are created, there will be only one copy of the static member.

Keyword static means that there is only one instance of the member in the class. Static variables are used to define constants because their values can be obtained by calling the class directly without creating an instance of the class. Static variables can be initialized outside the definition of a member function or class. You can also initialize static variables within the definition of the class.

The following example demonstrates the use of static variables:

Example

using System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s1 = new StaticVar();
            StaticVar s2 = new StaticVar();
            s1.count();
            s1.count();
            s1.count();
            s2.count();
            s2.count();
            s2.count();
            Console.WriteLine("s1's variable num: {0}", s1.getNum());
            Console.WriteLine("s2's variable num: {0}", s2.getNum());
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Variables of s1 num: 6
Variables of s2 num: 6

You can also declare a member function as static . Such functions can only access static variables. Static functions exist before the object is created. The following example demonstrates the use of static functions:

Example

using System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public static int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s = new StaticVar();
            s.count();
            s.count();
            s.count();
            Console.WriteLine("Variable num: {0}", StaticVar.getNum());
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Variable num: 3

Powered by TorCMS (https://github.com/bukun/TorCMS).