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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...