LoginSignup
14
13

More than 3 years have passed since last update.

【C#】文字列とenumの変換テクニック集

Posted at

はじめに

文字列とenumを相互に変換することが結構多いため、テクニック集としてまとめることにしました。
同じ境遇にあったC#erの皆さんにも伝わればいいなと思います。

サンプルコードで使用するenumを毎回記述するのは冗長なため、ここに記述しておきます。
(適当にサンプル用に定義しただけなので、このenumに意味はほとんどありません。)

enum Authority
{
    ReadWrite,  // 読み書き可能
    Read,       // 読み込み専用
    None        // 権限なし
}

文字列 から enum への変換

文字列からenumへ変換する際に整数型にキャストしてからenumへキャストしたりしていませんか?

Authority auth = (Authority)int.Parse("1");  // こんな感じ
Console.WriteLine(auth);
出力結果
Read

いちいち整数型にキャストするのは面倒ですよね。
Enum.Parse(Type, String)を使えば整数型へのキャストは不要です。

Authority auth = (Authority)Enum.Parse(typeof(Authority), "1");
Console.WriteLine(auth);
出力結果
Read

さらに嬉しいことにEnum.Parse(Type, String)は名称からenumを取得することもできます。

Authority auth = (Authority)Enum.Parse(typeof(Authority), "Read");
Console.WriteLine(auth);
出力結果
Read

名称の大文字小文字が合わないというときはEnum.Parse(Type, String, Boolean)を使いましょう。
第3引数にtrueを指定すれば、大文字と小文字を区別せずに変換できます。
ちなみに以下の例でtrueを指定しない場合はSystem.ArgumentExceptionが発生します。

Authority auth = (Authority)Enum.Parse(typeof(Authority), "read", true);
Console.WriteLine(auth);
出力結果
Read
trueを指定しない場合の出力結果
System.ArgumentException: 要求された値 'read' が見つかりませんでした。

.NET CoreであればEnum.Parseにジェネリックバージョンがあるようで、以下のような記述も可能です。
enumへのキャストが無い分スッキリした記述になっています。
.NET Frameworkでもできるようになるといいなぁ)

Authority auth = Enum.Parse<Authority>("Read");
Console.WriteLine(auth);
出力結果
Read
Authority auth = Enum.Parse<Authority>("1");
Console.WriteLine(auth);
出力結果
Read

enum から 文字列 への変換

今度は逆にenumから文字列へ変換する場合を考えてみます。
enumを整数型にキャストしてから文字列に変換したりしてませんか?

string authValue = ((int)Authority.ReadWrite).ToString(); // こんな感じ
Console.WriteLine(authValue);
出力結果
0

そんなときはEnum.ToString(String)を使って書式を指定すればキャストせずとも文字列を取得できます。
指定できる書式については、こちらを参照してください。

string authValue = Authority.ReadWrite.ToString("d");
Console.WriteLine(authValue);
出力結果
0

まとめ

文字列とenumの変換についてまとめてみました。
Enumクラスについてもっと知りたい場合はこちらのドキュメントをご覧ください。
この記事でC#のコードが少しでも綺麗になれば幸いです。

それではまた。
TomoProg

14
13
0

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
14
13