c sharp

C# IsNested Property

We can create nested classes,nested structure etc in C#. So, if we want to check if the type is nested or not, IsNested Property is used. Let’s create nested classes and nested structures and implement IsNested Property.

IsNested Property

The IsNested property from the Type class returns True if the Type is nested. Otherwise, False is returned.

Syntax:

bool typeof(Type).IsNested

Return Type:

It returns the Boolean value (True/False).

Example 1:

Let’s create a class and check if it is nested or not.

using System;
         
 //create class - Linuxhint
class Linuxhint
{
   
    static public  void Main(){
        //check the class Linuxhint is nested or not.
    Console.WriteLine("Is Linuxhint nested?:"+typeof(Linuxhint).IsNested);
}
}

Output:

Explanation:

Here, Linuxhint is a class and it is not nested inside any class or any Type. So, False is returned.

Example 2:

Let’s create an interface and Abstract class and check if they are Enum or not.
using System:

using System;
         
         
//create class Linux
class Linux{
    //this is a class
}
 //create class - Linuxhint
class Linuxhint
{
   
    static public  void Main(){
        //check if the class Linux is nested or not.
    Console.WriteLine("Is Linux nested in Linuxhint?:"+typeof(Linux).IsNested);
}
}

Output:

Explanation:

Here, Linux is a class and it is not nested inside any class or any Type. So, False is returned.

Example 3:

Let’s create a class named Linux inside the Linuxhint class and check if it is nested in Linuxhint or not.

using System;
       
 //create class - Linuxhint
class Linuxhint
{
   //create class Linux
class Linux{
    //this is a nested class
}
    static public  void Main(){
        //check if the class Linux is nested or not.
    Console.WriteLine("Is Linux nested in Linuxhint?:"+typeof(Linux).IsNested);
}
}

Output:

Explanation:

Here, Linux is a class and it is nested inside Linuxhint class. So, True is returned.

Example 4:

Let’s create a structure named Linux inside the Linuxhint class and check if it is nested in Linuxhint or not.

using System;
       
 //create a class - Linuxhint
class Linuxhint
{
   //create structure - Linux
struct Linux{
    //this is a structure nested inside class
}
    static public  void Main(){
        //check if the class Linux is nested or not.
    Console.WriteLine("Is Linux structure nested inside Linuxhint?:"+typeof(Linux).IsNested);
}
}

Output:

Explanation:

Here, Linux is a structure and it is nested inside Linuxhint class. So, True is returned.

Conclusion

Finally, we came to know that IsNested property is used to check if any Type is nested or not.
If any Type is nested inside any Type, True is returned. We have seen four different examples to demonstrate this property.

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain