An object reference is required for non-static field, method, or property in my controller

Possible Duplicate:
An object reference is required for the non-static field, method, or property

I have a non-static field:

private IDictionary<string, string> _mappings = 
    new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)

that I wnat to use inside of a action like this:

public static string GetMimeType(string extension)
{
    //...
    return _mappings.TryGetValue(extension, out mime) ? 
        mime : "application/octet-stream";
}

The compiler is complaining:

An object reference is required for non-static field, method, or
property in the return statement.

How can I reference this field?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You cannot access instance members from static members so you have 2 choices.

  1. Make the method an instance method (remove the static keyword)
  2. Make the field a static (add the static keyword)

The one you choose will depend on whether the field should be shared across all instances or not.

Method 2

I think the compiler is pretty clear here: Your GetMimeType method is a static method, but the _mappings variable is not declared static (an non-static or instance field/variable).

If you want to use the mappings variable as it appears above do this:

private static IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)

Edit: As the commenter pointed out below, you must be careful that this is actually the behavior you want. A static member means all instances will share this same mappings variable and can overwrite the data present. If you want one mappings variable per class, then you should change your method to an instance method (by removing the static keyword), as noted in the answer above.

Method 3

If you just want a dictionary of values that is populated once and never modified after that, a thing you could do would be make the dictionary static and populate it in a static constructor.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x