Errore del compilatore CS0165

Uso della variabile locale non assegnata "name"

Il compilatore C# non consente l'uso di variabili non inizializzate. Se tramite il compilatore viene rilevato l'utilizzo di una variabile che potrebbe non essere stata inizializzata, viene generato l'errore di compilazione CS0165. Per altre informazioni, vedere Campi. Questo errore viene generato quando il compilatore rileva un costrutto che potrebbe comportare l'uso di una variabile non assegnata, anche se il codice specifico non viene assegnato. Questo evita la necessità di regole eccessivamente complesse per l'assegnazione definita.

Per altre informazioni, vedere Why does a recursive lambda cause a definite assignment error? (Perché un'espressione lambda ricorsiva causa un errore di assegnazione definita?).

Esempio 1

L'esempio seguente genera l'errore 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();  
    }  
}  

Esempio 2

L'errore di compilazione CS0165 può verificarsi nelle definizioni di delegati ricorsivi. È possibile evitare l'errore definendo il delegato in due istruzioni in modo da non utilizzare la variabile prima che venga inizializzata. Nell'esempio seguente viene illustrato l'errore e la risoluzione.

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)