Edit

Share via


Compiler Error CS0815

Cannot assign 'expression' to an implicitly typed local

An expression that is used as the initializer for an implicitly typed variable must have a type. Because anonymous function expressions, method group expressions, and the null literal expression do not have a type, they are not appropriate initializers. An implicitly typed variable cannot be initialized with a null value in its declaration, although it can later be assigned a value of null. With C# version 10 Lambda expressions and method groups with natural types can be used as initializers in var declarations.

To correct this error

  1. Provide an explicit type for the variable.
  2. Or specify natural types with C# version 10 and higher.

Example

The following code generates CS0815:

// cs0815.cs  
class Test  
{  
    public static int Main()  
    {  
        var d = s => -1; // CS0815  
        var e = (string s) => 0; // CS0815 for C# versions before 10
        var p = null; // CS0815  
        var del = delegate(string a) { return -1; }; // CS0815  
        return -1;  
    }  
}  

See also