C# Error CS0831 – An expression tree may not contain a base access

C# Error

CS0831 – An expression tree may not contain a base access

Reason for the Error & Solution

An expression tree may not contain a base access.

A base access means to make a function call that would ordinarily be a virtual function call as a non-virtual function call on the base class method. This is not allowed in the expression tree itself, but you can invoke a helper method in your class that invokes the base class method.

To correct this error

  1. If you must access a base class method in this manner, create a helper method that calls into the base class and have the expression tree call the helper method. This technique is shown in the following code.

Example

The following example generates CS0831:

// cs0831.cs  
using System;  
using System.Linq;  
using System.Linq.Expressions;  
  
public class A  
{  
    public virtual int BaseMethod() { return 1; }  
}  
public class C : A  
{  
    public override int BaseMethod() { return 2; }  
    public int Test(C c)  
    {  
        Expression<Func<int>> e = () => base.BaseMethod(); // CS0831  
  
        // Try the following line instead,
        // along with the BaseAccessHelper method.  
        // Expression<Func<int>> e2 = () => BaseAccessHelper();  
        return 1;  
    }
    // Uncomment to call from e2 expression above.  
    // int BaseAccessHelper()  
    // {  
    //     return base.BaseMethod();  
    // }  
  
}

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