Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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#




// C# program to check whether a class is
// a sub-class of a specified class or not
using System;
  
// Create a class named Geeks
public class Geeks{}
  
// Create a subclass that is from Geeks class
public class smallGFG : Geeks{}
  
// Create a class named mygg
public class mygg{}
  
class GFG{
      
// Drived code
public static void Main()
{
      
    // Check the class is a subclass of the class
    // Using IsSubclassOf() method
    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#




// C# program to check whether a class is
// a sub-class of a specified class or not
using System;
  
// Create a class named Geeks
public class Mypet
{
    public void color()
    {
        Console.WriteLine("I like pink color hair");
    }
}
  
// Create a subclass that is from Mypet class
public class Dog : Mypet{}
  
class GFG{
      
// Driver code
public static void Main()
{
    
    // Check the class is a subclass of the class
    // Using IsSubclassOf() method
    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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!