c sharp

How to Use GetType for Type Identification in C#

One of the most basic concepts that you learn when you are starting in programming is data types. Data types refer to a set of classification of the data in a program that tells the compiler how to use and work with the data. This includes defining the operations that are supported on the data and the storage allocation.

When you get deeper into programming, you will go past the primitive data types and define the custom types to fit your application needs.

Therefore, you will come across such instances where you need to check the data type of a given variable. This can be very useful in type checking, reflection, dynamic object usage, and more.

In this tutorial, we will learn how to use the GetType() method in C# to discover how we can gather an information about the data type of a given variable at runtime.

The Basics of the GetType() Method

The GetType() method is part of the C# “System.Object” class. Hence, it is available to all objects in C#. This makes it easy to call and use on any supported data type.

The method itself returns an instance of the “Type” class which contains the metadata about the type of the object.

The method does not take any parameter as demonstrated in the following example syntax:

Type type = object.GetType();

Example 1: Basic Usage

Let us demonstrate how to use this method to gather the data types of various objects in a basic C# application.

We can run the code as follows:

using System;
class Program
{
static void Main()
{
        int integer = 5;
        string str = "String!";
        double dbl = 5.5;
        Console.WriteLine(integer.GetType());
        Console.WriteLine(str.GetType());
        Console.WriteLine(dbl.GetType());
    }
}

In this example, we use the GetType() method to get the data type of an integer, a string, and a double. The resulting output is as follows:

System.Int32
System.String
System.Double

Example 2: Conditional Type Checking

We perform the type checking using the GetType() method by employing the functionality of conditional statements. This can allow us to execute a specific code block if the value is of specific type and vice versa.

Consider the following example:

using System;

class Program
{
    static void Main()
    {
        object obj = "str";

        if (obj.GetType() == typeof(string))
        {
            Console.WriteLine("string type");
        }
        else
        {
            Console.WriteLine("!string.");
        }
    }

}

In this example, we start by defining a variable called “obj” that holds a string value. We then use the GetType() method to check whether the object is of type string. If true, we print a message to the console indicating that. Otherwise, we print a message which denotes that the value is not a string.

The resulting output is as follows:

string type

Example 3: Working with Arrays

We can also use the GetType() method to determine the type of arrays and their elements. This allows us to inspect the arrays type as demonstrated in the following code:

using System;
class Program
{
    static void Main()
    {
        int[] intArray = { 1, 2, 3, 4, 5 };

        Console.WriteLine(intArray.GetType());

        Type elementType = intArray.GetType().GetElementType();
        Console.WriteLine(elementType);
    }

}

As you can see from this example, we use the GetType() method to get the type of the intArray object. We then invoke the GetElementType on the “Type” object to fetch the type of elements in the array. The resulting output is as follows:

System.Int32[]
System.Int32

Example 4: Using GetType in Reflection

When it comes to working with metadata of various types, the GetType() method can play a crucial role as demonstrated in the following example:

using System;
using System.Reflection;
class Program
{
    static void Main()
    {
        string str = "str!";
        Type strType = str.GetType();
        PropertyInfo[] properties = strType.GetProperties();
        Console.WriteLine($"Properties of {strType.Name}:");
        foreach (var prop in properties)
        {
            Console.WriteLine(prop.Name);
        }
    }

}

In this one, we use the GetType() method to get the type of the object of a string. We then use the “Type” object to get the array of “PropertyInfo” objects which basically contains all the properties of a string data type. We then print the properties to the console as shown in the following output:

Properties of String:
Chars
Length

Conclusion

In this post, we explored the workings of the GetType() method in C# to gather the type information about various objects in C#.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list