HomeCSharpC# Error CS0825 – The contextual keyword ‘var’ may only appear within a local variable declaration or in script code

C# Error CS0825 – The contextual keyword ‘var’ may only appear within a local variable declaration or in script code

C# Error

CS0825 – The contextual keyword ‘var’ may only appear within a local variable declaration or in script code

Reason for the Error & Solution

The contextual keyword ‘var’ may only appear within a local variable declaration.

To correct this error

  1. If the variable belongs at class scope, give it an explicit type. Otherwise move it inside the method where it will be used.

Example

The following code generates CS0825 because var is used on a class field:

// cs0825.cs  
class Test  
{  
    // Both of these declarations trigger CS0825
    private var genreName;
    private var bookTitles = new List<string>();
  
    static int Main()  
    {  
        var totalBooks = 42; // var is OK here  
        return -1;  
    }  
}  

Leave a Reply

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...