Home »
.Net »
C# Programs
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 »