How to use virtual functions in C#

2 Answers

0 votes
using System;

class Parent
{
    public virtual void Display() { // Virtual function
        Console.WriteLine("This is the Parent class.");
    }
}

class Child : Parent
{
    public override void Display() { // Overriding the virtual function
        Console.WriteLine("This is the Child class.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Parent obj = new Child(); 
        
        obj.Display(); // Calls the Child Display method at runtime
    }
}


 
/*
run:
 
This is the Child class.

*/

 



answered Aug 3, 2025 by avibootz
0 votes
using System;

class Parent
{
    public virtual void Display() { // Virtual function
        Console.WriteLine("This is the Parent class.");
    }
}

class Child : Parent
{
   /*public override void Display() { // Overriding the virtual function
        Console.WriteLine("This is the Child class.");
    }*/
}

class Program
{
    static void Main(string[] args)
    {
        Parent obj = new Child(); 
        
        obj.Display(); // Calls the Parent Display method at runtime
    }
}


 
/*
run:
 
This is the Parent class.

*/

 



answered Aug 3, 2025 by avibootz

Related questions

1 answer 189 views
1 answer 173 views
1 answer 175 views
1 answer 179 views
1 answer 174 views
1 answer 192 views
...