コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】組み込み型の名前を「Int32」ではなく「int」という形式で取得する方法

ソースコード

using System;

namespace Kogane
{
    public static class TypeUtils
    {
        public static string GetCSharpTypeKeyword( Type type )
        {
            return GetCSharpTypeKeyword( type.Name );
        }

        // https://stackoverflow.com/questions/56352299/gettype-return-int-instead-of-system-int32
        // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in-types
        public static string GetCSharpTypeKeyword( string typeName )
        {
            return typeName switch
            {
                "Boolean" => "bool",
                "Byte"    => "byte",
                "SByte"   => "sbyte",
                "Char"    => "char",
                "Decimal" => "decimal",
                "Double"  => "double",
                "Single"  => "float",
                "Int32"   => "int",
                "UInt32"  => "uint",
                "Int64"   => "long",
                "UInt64"  => "ulong",
                "Int16"   => "short",
                "UInt16"  => "ushort",
                "Object"  => "object",
                "String"  => "string",
                "Void"    => "void",
                _         => typeName,
            };
        }
    }
}

通常

Debug.Log( typeof( int ).Name );    // Int32
Debug.Log( typeof( float ).Name );  // Single
Debug.Log( typeof( string ).Name ); // String

使用例

Debug.Log( TypeUtils.GetCSharpTypeKeyword( typeof( int ) ) );    // int
Debug.Log( TypeUtils.GetCSharpTypeKeyword( typeof( float ) ) );  // float
Debug.Log( TypeUtils.GetCSharpTypeKeyword( typeof( string ) ) ); // string