C# base Keyword

C# base Keyword

Inthis article, how to use base keyword in c#.

The base keyword is used in constructors. A derived class constructor is required to call the constructor from its base class.

Example:

So, this example shows how to specify the base-class constructor called when creating instances of a derived class.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace usingcsharp
{

    public class BaseClass
    {
        int num;

        public BaseClass()
        {
            Console.WriteLine("In BaseClass()");
        }

        public BaseClass(int j)
        {
            num = j;
            Console.WriteLine("In BaseClass(int j)");
        }

        public int GetNum()
        {
            return num;
        }
    }

    public class DerivedClass : BaseClass
    {
        static void Main()
        {
            DerivedClass md = new DerivedClass();
            DerivedClass md1 = new DerivedClass(10);
            Console.WriteLine("press any key");
            Console.ReadKey();
        }
        // This constructor will call BaseClass.BaseClass()
        public DerivedClass()
            : base()
        {
        }

        // This constructor will call BaseClass.BaseClass(int j)
        public DerivedClass(int j) : base(i)
        {
        }        
    }
    /*
    Output:
    In BaseClass()
    In BaseClass(int j)
    press any key
    */
}

2021-10-03