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

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