[C#] How to Determine Object Type Classifications (Value Type vs Class) at Runtime

In C#, by referencing properties of the Type class, you can determine classifications such as “is it a value type or reference type,” “is it an array,” or “is it a generic type” at runtime.

This information is extremely useful when creating libraries for generic processing or debugging methods.

目次

Key Classification Properties of the Type Class

Below is a list of commonly used properties in the System.Type class for determining type categories.

Property NameMeaningExample (Returns true)
IsValueTypeChecks if it is a value type (struct or enum).int, double, DateTime, struct
IsEnumChecks if it is an enumeration (Enum).DayOfWeek, System.IO.FileMode
IsArrayChecks if it is an array.int[], string[,]
IsClassChecks if it is a class (reference type).
(Includes strings, delegates, and arrays)
string, List<T>, object, class
IsGenericTypeChecks if it is a generic type.List<T>, Dictionary<TKey, TValue>

Google スプレッドシートにエクスポート

Implementation Sample of Type Determination

The following code passes objects of various types to the CheckType method and confirms which properties return true or false.

Sample Code

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        // Output header
        Console.WriteLine($"{"Type Name",-12} | Value | Enum  | Array | Class | Generic");
        Console.WriteLine(new string('-', 65));

        // Execute determination with various data types
        CheckType(10.3);                 // double (Value Type)
        CheckType("Hello");              // string (Class)
        CheckType(DayOfWeek.Saturday);   // Enum (Value Type and Enum)
        CheckType(new int[4]);           // int[] (Class and Array)
        CheckType(new List<int>());      // List<int> (Class and Generic)
    }

    /// <summary>
    /// Determine and display object type information
    /// </summary>
    static void CheckType(object obj)
    {
        if (obj == null) return;

        Type type = obj.GetType();

        // Display type name
        Console.Write($"{type.Name,-12} | ");

        // Display results of various classification properties
        // You could convert them to "Yes"/"No" for readability,
        // but here we display the bool values directly.
        Console.Write($"{type.IsValueType,-5} | ");
        Console.Write($"{type.IsEnum,-5} | ");
        Console.Write($"{type.IsArray,-5} | ");
        Console.Write($"{type.IsClass,-5} | ");
        Console.Write($"{type.IsGenericType,-5}");
        
        Console.WriteLine(); // New line
    }
}

Execution Result

Type Name    | Value | Enum  | Array | Class | Generic
-----------------------------------------------------------------
Double       | True  | False | False | False | False
String       | False | False | False | True  | False
DayOfWeek    | True  | True  | False | False | False
Int32[]      | False | False | True  | True  | False
List`1       | False | False | False | True  | True

Explanation and Notes

1. Relationship between Value Types and Classes

  • IsValueType: Returns true for int, double, struct, etc.
  • IsClass: Returns true not only for defined classes but also for arrays (which inherit from System.Array), strings (System.String), and delegates, as they are all reference types.

Therefore, an array will return true for both IsArray and IsClass.

2. IsPrimitive (Primitive Types)

Although not included in the table above, there is also a Type.IsPrimitive property. This returns true only for “basic types” like int, double, bool, and byte. Note that DateTime, decimal, and string are not primitives, so it returns false for them.

3. Handling Null

In the CheckType method of the sample code, calling GetType() on the argument obj if it is null would throw a NullReferenceException. You must perform a check at the beginning or ensure a null-safe implementation.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次