This is the 22nd day of my participation in the August Wen Challenge.More challenges in August

Class (Class) ❤️

When you define a class, you define a blueprint of data types. This doesn’t actually define any data, but it defines what the name of the class means, that is, what the objects of the class consist of and what operations can be performed on that object. An object is an instance of a class. The methods and variables that make up a class are called members of the class.


The definition of a class

A class definition begins with the keyword class, followed by the name of the class. The body of the class, enclosed in a pair of curly braces. Here is the general form of the 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}}Copy the code

Please note:

  • Access identifiers specify access rules for classes and their members. If not specified, the default access identifier is used. The default access identifier for a class is internal, and the default access identifier for members is private.
  • The data type specifies the type of the variable, and the return type specifies the data type returned by the returned method.
  • To access a member of a class, you use the dot (.). Operator.
  • The dot operator links the name of an object to the name of a member.

The following examples illustrate the concepts discussed so far:

The instanceusing System;
namespace BoxApplication
{
    class Box
    {
       public double length;   / / the length
       public double breadth;  / / width
       public double height;   / / height
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // declare Box1 of type Box
            Box Box2 = new Box();        // declare Box2 of type Box
            double volume = 0.0;         / / volume

            / / Box1 elaborate
            Box1.height = 5.0;
            Box1.length = 6.0;
            Box1.breadth = 7.0;

            / / Box2 elaborate
            Box2.height = 10.0;
            Box2.length = 12.0;
            Box2.breadth = 13.0;
           
            // The volume of Box1
            volume = Box1.height * Box1.length * Box1.breadth;
            Console.WriteLine("Box1 volume: {0}",  volume);

            // The volume of Box2
            volume = Box2.height * Box2.length * Box2.breadth;
            Console.WriteLine("Box2 volume: {0}", volume); Console.ReadKey(); }}}Copy the code

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

Box1 volume: 210 Box2 volume: 1560


Member functions and encapsulation

A member function of a class is a function that has its definition or stereotype in the class definition, just like any other variable. As a member of a class, it can operate on any object of the class and 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 concepts to set and get the values of different class members in a class:

The instanceusing System;
namespace BoxApplication
{
    class Box
    {
       private double length;   / / the 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()
       {
           returnlength * breadth * height; }}class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // declare Box1 of type Box
            Box Box2 = new Box();                // declare Box2 of type Box
            double volume;                               / / volume


            / / Box1 elaborate
            Box1.setLength(6.0);
            Box1.setBreadth(7.0);
            Box1.setHeight(5.0);

            / / Box2 elaborate
            Box2.setLength(12.0);
            Box2.setBreadth(13.0);
            Box2.setHeight(10.0);
       
            // The volume of Box1
            volume = Box1.getVolume();
            Console.WriteLine("Box1 volume: {0}" ,volume);

            // The volume of Box2
            volume = Box2.getVolume();
            Console.WriteLine("Box2 volume: {0}", volume); Console.ReadKey(); }}}Copy the code

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

Box1 volume: 210 Box2 volume: 1560


Constructor in C#

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

The constructor name 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:

The instanceusing System;
namespace LineApplication
{
   class Line
   {
      private double length;   // The line length
      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 the line length
         line.setLength(6.0);
         Console.WriteLine("Length of line: {0}", line.getLength()); Console.ReadKey(); }}}Copy the code

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

Object has created a line of length: 6

The default constructor does not take any arguments. But if you need a constructor that takes parameters you can take parameters, and that constructor is called a parameterized constructor. This technique allows you to assign an initial value to an object while creating it, as shown in the following example:

The instanceusing System;
namespace LineApplication
{
   class Line
   {
      private double length;   // The line length
      public Line(double len)  // Parameterize the 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("Length of line: {0}", line.getLength());
         // Set the line length
         line.setLength(6.0);
         Console.WriteLine("Length of line: {0}", line.getLength()); Console.ReadKey(); }}}Copy the code

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

Object created, length = 10 Line length: 10 line length: 6


Destructors in C#

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

The destructor name prefixes the name of the class with a wavy (~), and it returns no value and takes no arguments.

Destructors are used to free resources before terminating 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:

The instanceusing System;
namespace LineApplication
{
   class Line
   {
      private double length;   // The line length
      public Line()  // constructor
      {
         Console.WriteLine("Object created");
      }
      ~Line() // destructor
      {
         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 the line length
         line.setLength(6.0);
         Console.WriteLine("Length of line: {0}", line.getLength()); }}}Copy the code

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

Object created line length: 6 Object deleted


Static member of a C# class

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

The static keyword 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 inside the class definition.

The following example demonstrates the use of static variables:

The instanceusing System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public int getNum()
        {
            returnnum; }}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(Num: {0}, s1.getNum());
            Console.WriteLine(Num: {0}, s2.getNum()); Console.ReadKey(); }}}Copy the code

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

Num: 6 of s2

A member function can also be declared 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:

The instanceusing System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public static int getNum()
        {
            returnnum; }}class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s = new StaticVar();
            s.count();
            s.count();
            s.count();                  
            Console.WriteLine(Num: {0}, StaticVar.getNum()); Console.ReadKey(); }}}Copy the code

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

Variable num: 3


Conclusion 💬

This article covers some of the basics of C#, following up on a previous blog that covered arrays, strings, structs, enumerations, and classes in C#

Maybe it’s not all there, but that’s about it. I will continue to update when I have time