Compiler Error CS0165

Use of unassigned local variable 'name'

The C# compiler doesn't allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165. For more information, see Fields. This error is generated when the compiler encounters a construct that might result in the use of an unassigned variable, even if your particular code does not. This avoids the necessity of overly complex rules for definite assignment.

For more information, see Why does a recursive lambda cause a definite assignment error?.

Example 1

The following sample generates 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.  
        //    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();  

Example 2

Compiler error CS0165 can occur in recursive delegate definitions. You can avoid the error by defining the delegate in two statements so that the variable is not used before it is initialized. The following example demonstrates the error and the resolution.

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