C# program to check a class is a sub-class of a specified class or not

Here, we are going to learn how to check a class is a sub-class of a specified class or not in C#?
Submitted by Nidhi, on October 30, 2020

Here, we will check a class is a sub-class of a specified class or not using IsSubclassOf() method of Type class.

Program:

The source code to check a class is a sub-class of a specified class or not is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to check a class is sub-class of the specified class.

using System;
using System.Reflection;

class ABC
{ 
    public ABC()
    {
        Console.WriteLine("ABC: Contructor called");
    }
}

class XYZ:ABC
{
    public XYZ()
    {
        Console.WriteLine("XYZ: Contructor called");
    }
}


class Program
{
    static void Main()
    {
        Type type1 = typeof(ABC);
        Type type2 = typeof(XYZ);

        if (type2.IsSubclassOf(type1) == true)
        {
            Console.WriteLine("XYZ class is sub class of ABC class");
        }
        else
        {
            Console.WriteLine("XYZ class is not sub class of ABC class");
        }
    }
}

Output:

XYZ class is sub class of ABC class
Press any key to continue . . .

Explanation:

In the above program, we created three classes ABC, XYZ, and Program. Here, we inherited the ABC class into XYZ class.

The program class contains the Main() method. The Main() method is the entry point for the program. Here, we check a class is a subclass of a specified class using the IsSubclassOf() method of Type class and printed the appropriate message on the console screen.

C# Basic Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.