0

I try to call a method using reflection. My object :

public class CurrentSearch
{
    public string currentUniverse { get; set; }
    public string currentApplication;
    public string currentUsage;
...

My code :

CurrentSearch cS = SessionUtils.getCS();
cS.currentUniverse = "lol";         
string methodName = "currentUniverse" ;
var test = typeof(CurrentSearch).GetMethod(methodName).Invoke(cS, null);

But i get the error "Object reference not set to an instance of an object." on the last line. I've checked cS, it's not null... What's wrong? Thx

Lempkin
  • 1,241
  • 2
  • 16
  • 40

1 Answers1

1

currentUniverse is a property, so you need to use GetProperty, not GetMethod.

void Main()
{
    CurrentSearch cs = new CurrentSearch();
    cs.currentUniverse = "lol";         
    string methodName = "currentUniverse" ;
    Console.WriteLine(typeof(CurrentSearch).GetProperty(methodName).GetValue(cs));
                                            ^^^^^^^^^^^
}

public class CurrentSearch
{
    public string currentUniverse { get; set; }
    public string currentApplication;
    public string currentUsage;
}
RB.
  • 33,692
  • 12
  • 79
  • 121