未割り当てのローカル変数 'name' の使用
C# コンパイラでは、初期化されていない変数は使用できません。 初期化されていない可能性がある変数の使用をコンパイラが検出した場合、コンパイラ エラー CS0165 が生成されます。 詳細については、「フィールド」を参照してください。 このエラーは、割り当てられていない変数を使用した可能性があるコンストラクトにコンパイラが遭遇したときに生成されます。特定のコードで使用しないとしてもです。 これにより、複雑なルールでなくても確実な割り当てが可能になります。
詳細については、「Why does a recursive lambda cause a definite assignment error?」(再帰的なラムダで、明白な代入エラーが発生するのはなぜか) をご覧ください。
例 1
次の例では CS0165 が生成されます。
// CS0165.cs
using System;
class MyClass
{
public int i;
}
class MyClass2
{
public static void Main(string[] args)
{
// i and j are not initialized.
int i, j;
// You can provide a value for args[0] in the 'Command line arguments'
// text box on the Debug tab of the project Properties window.
if (args[0] == "test")
{
i = 0;
}
// If the following else clause is absent, i might not be
// initialized.
//else
//{
// i = 1;
//}
// Because i might not have been initialized, the following
// line causes CS0165.
j = i;
// To resolve the error, uncomment the else clause of the previous
// if statement, or initialize i when you declare it.
// The following example causes CS0165 because myInstance is
// declared but not instantiated.
MyClass myInstance;
// The following line causes the error.
myInstance.i = 0;
// To resolve the error, replace the previous declaration with
// the following line.
//MyClass myInstance = new MyClass();
}
}
例 2
コンパイラ エラー CS0165 は、再帰的な委任定義で発生します。 初期化前に変数が使用されないように、2 つのステートメントに委任を定義することでエラーを回避できます。 次の例では、エラーと解決策を示しています。
class Program
{
delegate void Del();
static void Main(string[] args)
{
// The following line causes CS0165 because variable d is used
// as an argument before it has been initialized.
Del d = delegate() { System.Console.WriteLine(d); };
//// To resolve the error, initialize d in a separate statement.
//Del d = null;
//// After d is initialized, you can use it as an argument.
//d = delegate() { System.Console.WriteLine(d); };
//d();
}
}
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET