Erro do Compilador CS0165

Uso de variável local não atribuída 'name'

O compilador C# não permite o uso de variáveis não inicializadas. Se o compilador detectar o uso de uma variável que pode não ter sido inicializada, ele gerará o erro do compilador CS0165. Para obter mais informações, consulte Campos. Esse erro é gerado quando o compilador encontra um constructo que pode resultar no uso de uma variável não atribuída, mesmo que o código específico não a use. Isso evita a necessidade de regras de atribuição definitiva exageradamente complexas.

Para saber mais, confira Por que uma lambda recursiva causa um erro de atribuição definido?.

Exemplo 1

O exemplo a seguir gera o erro 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();  
    }  
}  

Exemplo 2

O erro do compilador CS0165 pode ocorrer em definições de delegado recursivas. É possível evitá-lo definindo o delegado em duas instruções, para que a variável não seja usada antes da inicialização. O exemplo a seguir demonstra o erro e a resolução.

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();  
    }  
}  

Load(String)