0

How can I get the fields out of the parameter (is of type SomeObject) variable of the Doit-method()? I cannot change the signature of the Doit method and I cannot use the SomeObject in the Doit method.

 static void Main(string[] args)
    {
        Doit(typeof(SomeObject));
    }

    private static string Doit(object parameter)
    {
        var field = parameter.GetType().GetField("MyString");
        return field.GetValue("MyString").ToString();
    }

1 Answers1

0

I assume your parameter variable is of type SomeObject.

Normally, you would simply want to cast inside your method, like this:

private static string Doit(object parameter)
{
    var field = ((SomeObject)parameter).GetField("MyString");
    return field.GetValue("MyString").ToString();
}

If you truly don't have access to the SomeObject type from within that method, you can try using the dynamic keyword to allow for late-bound calls. It will look better than using the Reflection API. Like this:

private static string Doit(object parameter)
{
    var field = ((dynamic)parameter).GetField("MyString");
    return field.GetValue("MyString").ToString();
}

But beware, just like using the Reflection API, if you get your method calls wrong when using dynamic, the compiler will not be able to help you. It will fail at runtime.

EDIT

If you want to downvote, that's ok, but I do appreciate it when it comes accompanied by a constructive comment.

sstan
  • 35,425
  • 6
  • 48
  • 66