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.
// 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
};
You confused target-typed
newexpressions with anonymous types!new { ... }creates an anonymous type, soYYthere 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 typeXX, and also uses an object initialiser to initialise it.While object initialisers normally allow you to omit
()when there are no constructor parameters, target-typednewexpressions always require(), regardless of whether you are using an object initialiser. Otherwise, the syntax would conflict with anonymous types!