C# Error CS0815 – Cannot assign {0} to an implicitly-typed variable

C# Error

CS0815 – Cannot assign {0} to an implicitly-typed variable

Reason for the Error & Solution

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

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...