2
2

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 5 years have passed since last update.

ローカル変数の初期化タイミング

Posted at

初期化コードの方が前に書かれてないといけない様子。
コンパイラの盲点?

テストコード
static void Main()
{
    int x;
    string s = "10";
    validate(ref x, int.TryParse(s, out x));
    //TryParseが先に呼ばれてxは初期化されるはずだが・・・
    //「エラー	CS0165	未割り当てのローカル変数 'x' が使用されました。」
    Console.WriteLine(x);
}

//Parse成功なら範囲チェック、失敗ならデフォルト値をセット
private static void validate(ref int x, bool parseResult)
{
    int min = 1, max = 1000, defaultVal = 100;
    x = !parseResult ? defaultVal
        : x < min ? min
        : max < x ? max
        : x;
}
//逆順だと通る
private static void validate(bool parseResult, ref int x)
{
    validate(ref x, parseResult);
}


2
2
2

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?