C# Class

When you define a class, you define a blueprint for a data type. This does not actually define any data, but it defines what the class name means, that is, what the objects of the class consist of and what operations can be performed on this object. Objects are instances of the class. The methods and variables that make up a class are called members of the class.

Class definition

The definition of a class begins with the keywordclassBegin, followed by the class name. The body of the class, enclosed 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:

  • The access specifier <access specifier> specifies the access rules for the class and its members. If not specified, the default access specifier is used. The default access specifier for a class isinternal, and the default access identifier for members isprivate。
  • The data type <data type> specifies the type of a variable, and the return type <return type> specifies the data type returned by the method.
  • To access a member of a class, you use the dot (.) operator.
  • The dot operator links the object name and the member name.

The following example illustrates 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();        // Declare Box1 of type Box
            Box Box2 = new Box();        // Declare Box2 of type Box
            double volume = 0.0;         // volume

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

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

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

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

Box1 的体积: 210
Box2 的体积: 1560

Member functions and encapsulation

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

Member variables are attributes of an object (from a design perspective), and they remain private to achieve encapsulation. These variables can only be accessed using public member functions.

Let us use the concepts above 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();        // Declare Box1 of type Box
            Box Box2 = new Box();        // Declare Box2 of type Box
            double volume;               // volume


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

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

            // Volume of Box2
            volume = Box2.getVolume();
            Console.WriteLine("Volume of Box2: {0}", volume);
           
            Console.ReadKey();
        }
    }
}

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

Box1 的体积: 210
Box2 的体积: 1560

Constructors in C#

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

The constructor's name is exactly the same as the class name, 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;   // 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 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:

对象已创建
线条的长度: 6

Default constructorIt does not have any parameters. But if you need a constructor with parameters, it can have parameters; this kind of constructor is calledParameterized constructor. This technique can help you assign initial values to objects at the same time as creating them. See the following example for details:

Example


using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Line length
      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:

对象已创建,length = 10
线条的长度: 10
线条的长度: 6

Destructors in C#

ClassdestructorIt is a special member function of a class that is executed when an object of the class goes out of scope.

The destructor's name is the class name prefixed with a tilde (~). It does not return a value and does not take any parameters.

A destructor is used to release resources before ending a program (such as closing files, freeing memory, etc.). 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;   // 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 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:

对象已创建
线条的长度: 6
对象已删除

Static members of a C# class

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

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

The following example demonstratesStatic VariableUsage:

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:

s1 的变量 num: 6
s2 的变量 num: 6

You can also put aMember functiondeclared asstatic. Such functions can only access static variables. Static functions already exist before objects are created. The following example demonstratesStatic FunctionsUsage:

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:

变量 num: 3
other extensions