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?
You cannot access instance members from static members so you have 2 choices.
static
keyword)static
keyword)The one you choose will depend on whether the field should be shared across all instances or not.
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:
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.
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.