Last active
March 25, 2024 14:39
-
-
Save devlights/0a12cd3ae03c68e6c9e8 to your computer and use it in GitHub Desktop.
int.ParseとConvert.ToInt32の違い
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace DifferenceParseAndConvert | |
{ | |
using System; | |
class Program | |
{ | |
static void Main() | |
{ | |
// | |
// ParseメソッドとConvert.ToXXXメソッドの僅かな違い | |
// | |
// Parseメソッド、つまり、int.Parseなどのメソッドは | |
// 解析できない値、つまり、nullを設定すると例外が発生する。 | |
// | |
// しかし、Convert.ToXXXメソッドはnullを渡しても例外とはならず、処理される。 | |
// | |
// ただし、どちらの方法でも空文字を指定すると例外が発生する (FormatException) | |
// | |
string numberString = "123"; | |
string nullString = null; | |
string emptyString = string.Empty; | |
// | |
// int.Parseメソッド | |
// | |
Console.WriteLine("【****** int.Parse ******】"); | |
// 普通の数値文字列は成功 | |
Console.WriteLine(int.Parse(numberString)); | |
try | |
{ | |
// nullを渡すと当然エラー | |
Console.WriteLine(int.Parse(nullString)); | |
} | |
catch (ArgumentNullException nullEx) | |
{ | |
Console.WriteLine("int.Parse(null) ==> 例外発生, {0}", nullEx.Message); | |
} | |
try | |
{ | |
// 空文字でもエラー | |
Console.WriteLine(int.Parse(emptyString)); | |
} | |
catch (FormatException formatEx) | |
{ | |
Console.WriteLine("int.Parse('') ==> 例外発生, {0}", formatEx.Message); | |
} | |
// | |
// Convert.ToInt32メソッド | |
// | |
Console.WriteLine("\n【****** Convert.ToInt32 ******】"); | |
// 普通の数値文字列は成功 | |
Console.WriteLine(Convert.ToInt32(numberString)); | |
// nullを渡すとエラーにならず初期値が返る | |
Console.WriteLine(Convert.ToInt32(nullString)); | |
try | |
{ | |
// 空文字を渡すとエラー | |
Console.WriteLine(Convert.ToInt32(emptyString)); | |
} | |
catch (FormatException formatEx) | |
{ | |
Console.WriteLine("Convert.ToInt32('') ==> 例外発生, {0}", formatEx.Message); | |
} | |
// | |
// おまけ: | |
// int.TryParse | |
// | |
Console.WriteLine("\n【****** int.TryParse ******】"); | |
int i1; | |
int i2; | |
int i3; | |
Console.WriteLine(int.TryParse(numberString, out i1)); | |
Console.WriteLine(int.TryParse(nullString, out i2)); | |
Console.WriteLine(int.TryParse(emptyString, out i3)); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment