user34537
user34537

Reputation:

What does "a field initializer cannot reference non static fields" mean in C#?

I don't understand this error in C#

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

For the following code

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) { }
}

Upvotes: 13

Views: 18186

Answers (4)

Rene
Rene

Reputation: 2155

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

Upvotes: 8

zoidbeck
zoidbeck

Reputation: 4151

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.

Upvotes: 1

thecoop
thecoop

Reputation: 46098

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.

Upvotes: 17

shahkalpesh
shahkalpesh

Reputation: 33474

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

OR

Initialize the dictionary in the constructor.

Upvotes: 2

Related Questions