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!
First of all, I would recommend running this code in the debugger and turning one “Break on Exception” to help isolate which line causes the error. This is a useful debugging technique that can help you find these types of problems more quickly in the future. Go to
Debug >> Exceptionsin VS and check the checkbox forCommon Language Runtime Exceptionsin theThrowncolumn.Now for your issue. It’s likely that
senderis passed in asnull. If so, the line:will throw a
NullReferenceException. Instead, you can use:which identifies the type of the generic paramter without requiring an instance of it.
Now, without knowing more about what your code is trying to do, it’s impossible to say whether instantiating an instance of
Tis the right thing to do. Just because ReSharper recommends addingwhere T : new()doesn’t mean it’s appropriate – unless you know that that’s the right behavior.Finally, I don’t know if there is a compelling reason for using reflection to invoke
MethodInOtherClass– perhaps there is. But since you’re new to C#, I’ll mention that if the typeTwill always be a subclass of some base typeAor will always implement some interfaceIthat includes the method you want to call, you can simply apply a generic constraint to let the compiler know this. Then you can call the method without reverting to using reflection:Much nicer.
One final comment. It’s unusual to pass in an argument to a method, and then ignore it completely – only to instantiate an instance within the method. There are cases when it’s appropriate – but I tend to view it as a code smell. If possible, I would try to either get rid of the
senderargument, or change the code to first test it for null and instantiate only then.