What does System.Reflection.TargetException: Non-static method requires a target. mean?

a.toraby picture a.toraby · Feb 5, 2015 · Viewed 33.3k times · Source

In my application I receive the functionCode value from somewhere and need to reflect the appropriate class. I tried to reflect the appropriate type According to this solution. but it doesn't work for me. I can not use GetField() method because I'm working on a PCL project. Therefore I tried these lines of code:

AssemblyName name = new AssemblyName("MyLibrary");
var type = Assembly.Load(name);
type.DefinedTypes.FirstOrDefault(x =>
x.GetDeclaredProperty("functionCode") != null &&
 (byte)x.GetDeclaredProperty("functionCode").GetValue(null) == val);

It does not work too. It throws System.Reflection.TargetException: Non-static method requires a target.

Answer

Selman Genç picture Selman Genç · Feb 5, 2015

It means non static method requires an object. If you have an instance member then you have to use an instance to get it's value. Because without an instance it doesn't exist.So you need to pass an instance of the type instead of null to GetValue method.Or make the member static if you don't want it to be an instance member.