.NET 2.0: Invoking Methods Using Reflection And Generics Causes Exception

Posted by David Derringer on Stack Overflow See other posts from Stack Overflow or by David Derringer
Published on 2010-06-14T21:05:37Z Indexed on 2010/06/14 21:22 UTC
Read the original article Hit count: 212

Filed under:
|
|
|
|

Hi all,

I'm new to Stack Overflow, so forgive me. I've just started transititoning over to C# and I am stuck on a problem.

I am wanting to pass a generic class in and call a method from that class. So, my code looks as such:

public void UpdateRecords<T>(T sender) where T : new() //where T: new() came from Resharper
{
    Type foo = Type.GetType(sender.GetType().ToString());
    object[] userParameters = new object[2];
    userParameters[0] = x;
    userParameters[1] = y;
    sender = new T(); //This was to see if I could solve my exception problem
    MethodInfo populateRecord = foo.GetMethod("MethodInOtherClass");
    populateMethod.Invoke(sender, userParameters);
}

Exception thrown: "Object reference not set to an instance of an object."

Again, I really apologize, as I am nearly brand new to C# and this is the first time I've ever handled reflection and generics. Thank you!

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET