Call override function from base class c#

Thamotharan 21 Reputation points
2021-08-10T02:08:12.183+00:00

Given the following C# class definitions and code:

    public class Test
    {
        public void name()
        {
            printName();
        }
        protected virtual void printName()
        {
            Console.WriteLine("name");
        }
    }
    public class Test1 : Test
    {
        protected override void printName()
        {
            Console.WriteLine("name1");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            new Test().name();
        }
    }

Output is "name"
But I am excepting output is "name1"
How can I do it?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

Accepted answer
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-08-10T03:20:15.04+00:00

    Hi Thamotharan-5143,
    You cannot explicitly call the base function from outside the scope of Test or Test1.
    And Sasha Truf has pointed out that you can edit MSIL instead of C# to achieve it.
    More details you can refer to this thread.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. RLWA32 43,306 Reputation points
    2021-08-10T11:00:30.25+00:00

    If I correctly understand what you want to do the following should meet your objective.

    Test t = new Test();
    t.name(); // Output is "name"
    
    Test tBase = new Test1();
    tBase.name(); // Output is "name1"