Jonathan Edgardo
Jonathan Edgardo

Reputation: 513

Reflection Invoke With Parameters c# Error

I get this error

'System.Reflection.TargetException', The object does not match target type.

This is my Class

public clas Service 
{
  public DataTable ArticlesGet(string SearchValue = null, string SearchColumn = null, string SearchOperator = "%")
  {

    //Methods Here
  }
}

This is my Reflection Code

object obj = new Service();
Type Type = obj.GetType();
MethodInfo MethodInfo = Type.GetMethod("ArticlesGet");
MethodInfo.Invoke(Type, new object[] { "", "", "%" });  // Error

Thank You in advance.

Upvotes: 0

Views: 470

Answers (4)

Yazan Fahad Haddadein
Yazan Fahad Haddadein

Reputation: 533

Just you need to fix the line No 4 where you invoke your method, you need to pass the object instance instead of passing class Type object.

object obj = new Service();
Type Type = obj.GetType();
MethodInfo MethodInfo = Type.GetMethod("ArticlesGet");
var dataTableObject = MethodInfo.Invoke(obj, new object[] { "", "", "%" });

Upvotes: 1

daniele3004
daniele3004

Reputation: 13880

Try this simple way, it's simple and clear code:

   Type ty = typeof(Service);
   Service myTypeObject = (Service)Activator.CreateInstance(ty);

    DataTable myDataTable = myTypeObject.ArticlesGet("SearchValue", "SearchColumn", "SearchOperator");

Upvotes: 2

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You need to provide the instance on which you want to invoke that method, not its type:

DataTable table = (DataTable) MethodInfo.Invoke(obj, new object[] { "", "", "%" }); 

Upvotes: 1

Moho
Moho

Reputation: 16498

The first argument to Method.Invoke is the instance of the object, which should be obj in your case, not Type

Upvotes: 1

Related Questions