[C#] How to Get Object Type Information at Runtime Using GetType()

In C#, the GetType() method is defined in the System.Object class, which serves as the base for all classes. By using this method, you can retrieve exact type information (System.Type object) of an instance while the program is running.

This is used to identify the “actual type (dynamic type)” allocated in memory, rather than the “variable type (static type).” It is particularly useful for reflection, logging, and debugging.

目次

Sample: Getting Type Information with GetType

The following code analyzes the actual types of various data stored in an object array and displays their class names and namespaces.

Sample Code

using System;

public class Program
{
    public static void Main()
    {
        // Collection containing instances of different types
        // All variable types are treated as 'object' here
        var mixedData = new object[]
        {
            42,                         // System.Int32
            3.14159,                    // System.Double
            19800m,                     // System.Decimal
            "System Configuration",     // System.String
            DateTime.UtcNow,            // System.DateTime
            new Uri("https://example.com"), // System.Uri
            new CustomLogger()          // Custom class
        };

        Console.WriteLine($"{"Class Name",-15} | {"Namespace",-18} | FullName");
        Console.WriteLine(new string('-', 70));

        foreach (var obj in mixedData)
        {
            // Call GetType() to get runtime type information (Type object)
            Type t = obj.GetType();

            // Retrieve various properties from the Type object
            // Name: Class name only
            // Namespace: The namespace it belongs to
            // FullName: Full name including the namespace
            Console.WriteLine($"{t.Name,-15} | {t.Namespace,-18} | {t.FullName}");
        }
    }
}

// Custom class for verification
public class CustomLogger
{
}

Execution Result

Class Name      | Namespace          | FullName
----------------------------------------------------------------------
Int32           | System             | System.Int32
Double          | System             | System.Double
Decimal         | System             | System.Decimal
String          | System             | System.String
DateTime        | System             | System.DateTime
Uri             | System             | System.Uri
CustomLogger    | Program+CustomLogger | Program+CustomLogger

(Note: The output for CustomLogger may vary depending on the environment context, such as being a nested class).

Explanation and Important Points

Differences in Retrievable Properties

You can retrieve detailed information about a type from the System.Type object. Here are the differences between the main properties:

  • Name: Returns only the name of the class or structure (e.g., Int32).
  • Namespace: Returns the namespace to which the type belongs (e.g., System).
  • FullName: Returns the fully qualified name including the namespace (e.g., System.Int32). It does not include assembly information.

Returns the Actual Type

Even if a variable is declared as an object type or an interface type, GetType() always returns the type used when the instance was created (when new was called). This allows you to identify the true nature of the object you are handling, even when polymorphism is involved.

Beware of NullReferenceException

Since GetType() is an instance method, calling it on a variable that is null will cause a NullReferenceException. When dealing with variables that might be null, you must perform a null check beforehand.

object item = null;
// item.GetType(); // This throws an exception

if (item != null)
{
    Console.WriteLine(item.GetType().Name);
}
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次