0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#の列挙型についてのアウトプット

0
Last updated at Posted at 2025-01-13

C#の列挙型について学んだことをアウトプットします。

確認は .NET9 で行っています。

列挙型はクラスなどの定義と同じように宣言します。

enum Name
{
    Shion,
    Marine,
    Lamy,
}

class Program
{
    static void Main()
    {
        Console.WriteLine(Name.Shion);
        Console.WriteLine(Name.Marine);
        Console.WriteLine(Name.Lamy);
    }
}

// Shion
// Marine
// Lamy

C#の列挙型は内部的にint型の数値を持っているようで、
自動的に0, 1, 2と割り振られていくようです。

また、列挙型は数値であれば別の型を内部の型として定義可能です。
string型など数値以外は定義できないようです。

この内部数値を使用して比較処理などを行う場合は明示的にキャストする必要があります。

enum Name2: short
{
    Shion,
    Marine,
    Lamy,
}

class Program
{
    static void Main()
    {
        for (short i = 0; i < 3; i++)
        { 
            switch(i)
            {
                case (short)Name.Shion:
                    Console.WriteLine("紫咲シオン");
                    break;
                case (short)Name.Marine:
                    Console.WriteLine("宝鐘マリン");
                    break;
                case (short)Name.Lamy:
                    Console.WriteLine("雪花ラミィ");
                    break;
            }
        }
    }
}

// 紫咲シオン
// 宝鐘マリン
// 雪花ラミィ

数値であればプログラマー側で任意の値を設定することが可能です。

enum Name3
{
    Shion = 3,
    Marine = 10,
    Lamy = 55,
}

class Program
{
    static void Main()
    {
        if ((int)Name3.Shion == 3)
        {
            Console.WriteLine("Name3.Shionに割りられた数値は3です。");
        }
        if ((int)Name.Shion != 3)
        {
            Console.WriteLine("そのため、3以外の数値は一致しません。");
        }

        Console.WriteLine();
    }
}

// Name3.Shionに割りられた数値は3です。
// そのため、3以外の数値は一致しません。
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?