Tuesday 24 May 2016

Non static field requires a target c# error solution

non static field requires a target c#

Was getting while trying to get name and value of declared fields in a class using Reflection.

CodeClass doc = new CodeClass();
var errorMessage = doc.GetType().GetFields().Where(f => f.FieldType == typeof(System.Int16) && (Int16) f.GetValue(null) == 1).Select(o => o.Name).FirstOrDefault();
Console.WriteLine(errorMessage);

class CodeClass
{
public Int16 Error_Unknown_Document_Type_Enum = 1;
}

Solution 1 Add static keyword
class CodeClass
{
public static Int16 Error_Unknown_Document_Type_Enum = 1;
}