2
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?

cast / Parse / TryParse / Convert の違い

Posted at

1. cast(キャスト)

「互換性のある型同士」で使うシンプルな変換方法 です。
数値型の変換や、継承関係にあるクラスの変換などに使えます。

double d = 3.14;
int i = (int)d; // i = 3(小数点切り捨て)

ただし、互換性がない型に使うと例外が発生します。
stringint のような変換はできません。

2. Parse

「文字列を特定の型に変換する」メソッド です。
int, double, DateTime などの基本型には Parse が用意されています。

string s = "123";
int i = int.Parse(s); // i = 123

ただし、変換できない文字列だと 例外 (FormatException) が発生します。

3. TryParse

Parse の 安全版 です。
例外を出さず、変換できなければ false を返してくれます。

string s = "456";
if (int.TryParse(s, out int i))
{
    Console.WriteLine(i); // 456
}
else
{
    Console.WriteLine("変換できません");
}

ユーザー入力など「失敗する可能性がある文字列」を扱う場合は 必ず TryParse を使うのがおすすめです。

4. Convert

System.Convert クラスを使うと、幅広い型変換がまとめてできる ようになります。
特に null を扱える点が便利。

string s = "789";
int i = Convert.ToInt32(s); // i = 789

string nullStr = null;
int j = Convert.ToInt32(nullStr); // j = 0(例外ではない!)

double d = Convert.ToDouble(true); // d = 1

まとめ

方法 主な用途 失敗時の挙動
cast 互換性のある型変換 例外
Parse 文字列 → 型 例外
TryParse 文字列 → 型(安全版) false
Convert 幅広い型変換、null対応 デフォルト値 or 例外
2
0
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
2
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?