C# Program to Check a Class is a Sub-Class of a Specified Class or Not
Last Updated :
23 Nov, 2021
A class is a collection of methods, variables, and objects. A subclass is a class that is extended from the parent class. It should achieve all the properties from the parent class. Its syntax is similar to a class. Using: operator we can create the subclass. We can check the class is a subclass of the specific class or not by using the IsSubclassOf() method of the Type class. Or we can say that IsSubclassOf() method is used to check whether the current Type is derived from the given type. It will return true if the subclass is specific to the parent class. Otherwise, it will return false. This method will throw ArgumentNullException when the class name is null type. This method is used to:
- Check whether the class is derived from another class.
- Check whether a type is derived from the ValueType.
- Check whether the type is derived from Enum.
- Check whether a type is derived from the delegate.
Syntax:
public virtual bool IsSubclassOf(Type c);
Example 1:
C#
using System;
public class Geeks{}
public class smallGFG : Geeks{}
public class mygg{}
class GFG{
public static void Main()
{
Console.WriteLine( typeof (smallGFG).IsSubclassOf( typeof (Geeks)));
Console.WriteLine( typeof (Geeks).IsSubclassOf( typeof (smallGFG)));
Console.WriteLine( typeof (mygg).IsSubclassOf( typeof (Geeks)));
}
}
|
Output:
True
False
False
Example 2:
C#
using System;
public class Mypet
{
public void color()
{
Console.WriteLine( "I like pink color hair" );
}
}
public class Dog : Mypet{}
class GFG{
public static void Main()
{
if ( typeof (Dog).IsSubclassOf( typeof (Mypet)) == true )
{
Console.WriteLine( "Given class is a sub class" );
}
else
{
Console.WriteLine( "Given class is not a sub class" );
}
}
}
|
Output:
Given class is a sub class
Share your thoughts in the comments
Please Login to comment...