c accesses the this keyword and the base keyword examples

  • 2020-06-01 10:52:15
  • OfStack

Specifies the base class constructor to call when creating a derived class instance;

Calls methods that have been overridden by other methods on the base class.

Note: you cannot use the base keyword from static methods. The base keyword can only be used in instance constructors, instance methods, or instance accessors.

Example: examples of access keywords this and base; Create the base class Person, which contains two array members name and age, one constructor with two arguments, and one virtual function GetInfo() to display the contents of the data members name and age. Create a derived class Student, including one data member studentId, one derived class constructor with three parameters, and display the contents of name and age with: base calling the base class constructor, rewriting the virtual method GetInfo() of the inherited base class, and calling the methods of the base class.


namespace ConsoleApplication 
{
    public class Person  // Base class, equivalent public class Person : Object
    {
        public string name;
        public uint age;
        public Person(string name,uint age)// The constructor of the base class 
        {
            this.name = name; //this  The keyword refers to the current instance of the class 
            this.age = age; //this  The keyword refers to the current instance of the class 
        }
        public virtual void GetInfo()
        {
            Console.WriteLine("Name: {0}",name);
            Console.WriteLine("Age:{0}",age);
        }
    }
    public class Student:Person// Derived classes 
    {
        public string studentId;
        // A combination of derived class constructors :base Call the base class constructor 
        public Student(string name,uint age,string studentId):base(name,age)
        {
            this.studentId = studentId;
        }
        public override void GetInfo()
        {
            // Call the base class method 
            base.GetInfo();
            Console.WriteLine("StudentId: {0}",studentId);
        }
    }
 
   public class Program
    {

        static void Main(string[] args)
        {
            Student objstudent=new Student("jeamsluu",99,"20140101011");
            objstudent.GetInfo();
            Console.ReadKey();
        }
    }
}


Related articles: