Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot assign an Action property

Must be going crazy here but I can’t see what I’m doing wrong in the following code to cause the syntax error

CS0828: Cannot assign ‘method group’ to anonymous type property

I can’t see anything anonymous about the code, the property has a name. The method I assign it it is named etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    // A basic function that takes an int and has void return
    private static void DoSomething(int d) 
    {
        // .... do stuff
    };

    // A class is defined with an Action<int> delegate
    private class XX
    {
        public Action<int> YY { get; set; }
    }

    // An instance of the class which clearly assigns a known method to the property
    private static readonly XX xx = new
    {
        // error "CS0828: Cannot assign 'method group' to anonymous type property"
        YY = DoSomething
    };

>Solution :

You confused target-typed new expressions with anonymous types!

new { ... } creates an anonymous type, so YY there is a property of the anonymous type, so the compiler doesn’t know what delegate type it should convert the method group into.

You should use new() { ... } instead, which creates an object of the target type XX, and also uses an object initialiser to initialise it.

While object initialisers normally allow you to omit () when there are no constructor parameters, target-typed new expressions always require (), regardless of whether you are using an object initialiser. Otherwise, the syntax would conflict with anonymous types!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading