mercredi 21 novembre 2018

TargetParameterCountException when iteratively retrieving value out of reflexive properties of a string

Some context first :

I was writing a reusable "null tester" method that will be used to check if any variable of an object has a null or empty value. the goal is that the method can take an Object and use reflexion to check the value of each property.

Everything worked until I added a List<string> to a class that is being checked. While adding List<string> raised the TargetParameterCountException other primitive types didn't. The only other time I managed to reproduce this error is when I passed directly a string.

I managed to boil down this problem to that bit of code :

string toCheck = "foo";
var elementProperties = toCheck.GetType().GetProperties();
foreach (PropertyInfo property in elementProperties)
{
    var elementValue = property.GetValue(toCheck);
    //Check if "toCheck" is null or empty here
}

elementProperties has two Values

  • An Int32 Length
  • A Char Chars[Int32]

My understanding would be that the first represent the length and the second the content of the string. But when the code tries to "GetValue()" the second property it raises a TargetParameterCountException.

Does someone know why it would do that ?





Aucun commentaire:

Enregistrer un commentaire