Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program to Check a Specified Type is an Array or Not

  • Last Updated : 07 Jan, 2022

In C#, an array is a group of homogeneous elements that are referred to by a common name. So in this article, we will discuss how to check the variable is of array type or not. To do this task, we use the IsArray property of the Type class. This property is used to determine whether the specified type is an array or not. IsArray property will return true if the specified type is an array. Otherwise, it will return false. 

Syntax:

public bool IsArray{get;}

Return: It will return true if the value is an array otherwise false.

Approach

  • Import System.Reflection namespace.
  • Declare an array with a datatype of a size n.
  • Use IsArray is the method to check the type is array or not along with GetType() method. GetType() method method gets the type of the variable.
array.GetType().IsArray
  • If the condition is true then display “Type is array” or if the condition is false then display “Type is not array”.

Example 1: 

C#




// C# program to determine whether the
// specified type is an array or not
using System;
using System.Reflection;
 
class GFG{
     
static void Main()
{
     
    // Declare an array with size 5
    // of integer type
    int[] array1 = new int[5];
 
    // Check whether the variable is array or not
    // Using IsArray property
    if (array1.GetType().IsArray == true)
    {
        Console.WriteLine("Type is array");
    }
    else
    {
        Console.WriteLine("Type is not array");
    }
}
}

Output:

Type is array

Example 2:

C#




// C# program to determine whether the
// specified type is an array or not
using System;
using System.Reflection;
 
class GFG{
     
static void Main()
{
 
    // Declare and initializing variables
    int array1 = 45;
    string array2 = "GeeksforGeeks";
    int[] array3 = new int[3];
    double[] array4 = { 2.3, 4.5, 0.33 };
 
    // Check whether the variable is of array type or not
    // Using IsArray property
    Console.WriteLine("Is the type of array1 variable is array?" +
                      array1.GetType().IsArray);
    Console.WriteLine("Is the type of array2 variable is array?" +
                      array2.GetType().IsArray);
    Console.WriteLine("Is the type of array2 variable is array?" +
                      array3.GetType().IsArray);
    Console.WriteLine("Is the type of array2 variable is array?" +
                      array4.GetType().IsArray);
}
}
Output
Is the type of array1 variable is array?False
Is the type of array2 variable is array?False
Is the type of array2 variable is array?True
Is the type of array2 variable is array?True


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!