views:

1057

answers:

4

I dont understand this error in C#.

error CS0236: A field initializer cannot reference the non-static field, method, or property 'Prv.DB.getUserName(long)'

    public class MyDictionary<K, V>
    {
        //...
        public delegate V NonExistentKey(K k);
        NonExistentKey nonExistentKey;

        public MyDictionary(NonExistentKey nonExistentKey_) { //...
        }
    }

    class DB
    {
        SQLiteConnection connection;
        SQLiteCommand command;

        MyDictionary<long, string> usernameDict = new MyDictionary<long, string>(getUserName);

        string getUserName(long userId)
        {
            command.CommandText = "SELECT name FROM userdata WHERE userId=@userId;";
            command.Parameters.Add("@userId", DbType.Int64).Value = userId;
            return (string)command.ExecuteScalar();
        }
    };
A: 

getUserName is an instance method.
Change it to static, that might work.

OR

Initialize the dictionary in the constructor.

shahkalpesh
+3  A: 

Any object initializer used outside a constructor has to refer to static members, as the instance hasn't been constructed until the constructor is run, and direct variable initialization conceptually happens before any constructor is run. getUserName is an instance method, but the containing instance isn't available.

To fix it, try putting the usernameDict initializer inside a constructor.

thecoop
A: 

You cannot do this because the instance has to be initialized before you can access the properties of its class. The field initializers are called before the class is initialized.

If you want to initialize the field usernameDict with the return-value of the GetUserName-Method you have to do it within the constructor or make the Method a static one.

zoidbeck
A: 

The links below may shed some light on why doing what you are trying to do may not be such a good thing, in particular the second link:

Why Do Initializers Run In The Opposite Order As Constructors? Part One

Why Do Initializers Run In The Opposite Order As Constructors? Part Two

Rene