Initialize a dictionary that stores functions in C# - Stack Overflow

admin2025-04-17  2

I have program that looks like below. I want to initialize a dictionary that stores functions. However, the compiler does not allow me to do it, as is shown below. I get the error:

CS1950 The best overloaded Add method 'Dictionary<Func, string>.Add(Func, string)' for the collection initializer has some invalid arguments FuncDictonaryTest

But it works fine if I try to do in in the constructor. Why?

namespace FuncDictonaryTest
{
    internal class Program
    {
        private Dictionary<Func<bool>,
                           string> FunctionDictonary = new()
                           {
                                { TestA, "Hello" },
                                { TestB, "Byebye" }, // Not working
                            };        
        
        private Dictionary<Func<bool>,
                           string> FunctionDictonaryTwo;

        Program()
        {
            FunctionDictonaryTwo = new() // Working
            {   
                { TestA, "Hello" },
                { TestB, "Byebye" }
            };
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }

        private bool TestA()
        {
            return true;
        }        
        
        private bool TestB()
        {
            return false;
        }
    }
}

I have program that looks like below. I want to initialize a dictionary that stores functions. However, the compiler does not allow me to do it, as is shown below. I get the error:

CS1950 The best overloaded Add method 'Dictionary<Func, string>.Add(Func, string)' for the collection initializer has some invalid arguments FuncDictonaryTest

But it works fine if I try to do in in the constructor. Why?

namespace FuncDictonaryTest
{
    internal class Program
    {
        private Dictionary<Func<bool>,
                           string> FunctionDictonary = new()
                           {
                                { TestA, "Hello" },
                                { TestB, "Byebye" }, // Not working
                            };        
        
        private Dictionary<Func<bool>,
                           string> FunctionDictonaryTwo;

        Program()
        {
            FunctionDictonaryTwo = new() // Working
            {   
                { TestA, "Hello" },
                { TestB, "Byebye" }
            };
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }

        private bool TestA()
        {
            return true;
        }        
        
        private bool TestB()
        {
            return false;
        }
    }
}
Share Improve this question edited Jan 30 at 21:08 Guru Stron 144k11 gold badges172 silver badges212 bronze badges asked Jan 30 at 20:46 KGB91KGB91 6852 gold badges8 silver badges31 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

You should actually get here two errors (per element in the collection), the second one explaining the actual problem (demo @sharplab):

error CS1921: The best overloaded method match for 'Program.TestA()' has wrong signature for the initializer element. The initializable Add must be an accessible instance method.

If you change TestA to () => TestA() in the field initialization the error become even more evident (demo @sharplab):

private Dictionary<Func<bool>, string> FunctionDictonary = new()
{
    { () => TestA(), "Hello" },
    { () => TestB(), "Byebye" },
};  

error CS0236: A field initializer cannot reference the non-static field, method, or property 'Program.TestA()'
error CS0236: A field initializer cannot reference the non-static field, method, or property 'Program.TestB()'

You can't use non-static members in field/properties initializers.

The field docs can explain a bit why:

A field can be given an initial value by using the assignment operator when the field is declared.
Fields are initialized immediately before the constructor for the object instance is called.

And

A field initializer cannot refer to other instance fields.

If you'll make TestA and TestB methods static the errors will go away too (demo @sharplab)

转载请注明原文地址:http://anycun.com/QandA/1744891015a89085.html