C# Error CS0828 – Cannot assign ‘{0}’ to anonymous type property

C# Error

CS0828 – Cannot assign ‘{0}’ to anonymous type property

Reason for the Error & Solution

Cannot assign ‘expression’ to anonymous type property.

An anonymous type cannot be initialized with a null value or an unsafe type, or a method group or anonymous function.

To correct this error

  1. Either add a type declaration to the left side of the assignment, or change the expression on the right side so that it has an acceptable type.

Example

The following code generates CS0828 because a member of an anonymous type cannot be initialized with a null value.

// cs0828.cs  
using System;  
  
public class C  
{  
    public static int Main()  
    {  
        var a = 1;  
        var c = new { p1 = null }; // CS0828  
        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...