C# Program to Check a Specified Type is an Array or Not
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#
using System;
using System.Reflection;
class GFG{
static void Main()
{
int [] array1 = new int [5];
if (array1.GetType().IsArray == true )
{
Console.WriteLine( "Type is array" );
}
else
{
Console.WriteLine( "Type is not array" );
}
}
}
|
Output:
Type is array
Example 2:
C#
using System;
using System.Reflection;
class GFG{
static void Main()
{
int array1 = 45;
string array2 = "GeeksforGeeks" ;
int [] array3 = new int [3];
double [] array4 = { 2.3, 4.5, 0.33 };
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
Last Updated :
07 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...