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

2

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh yes that was pretty obvious ^^ Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.