Compiler Error CS0165


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Use of unassigned local variable 'name'

The C# compiler does not 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. Note that 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

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

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