Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TargetParameterCountException when enumerating through properties of string

I'm using the following code to output values of properties:

string output = String.Empty;
string stringy = "stringy";
int inty = 4;
Foo spong = new Foo() {Name = "spong", NumberOfHams = 8};
foreach (PropertyInfo propertyInfo in stringy.GetType().GetProperties())
{
  if (propertyInfo.CanRead) output += propertyInfo.GetValue(stringy, null);
}

If I run this code for the int, or for the Foo complex type, it works fine. But if I run it for the string (as shown), I get the following error on the line inside the foreach loop:

System.Reflection.TargetParameterCountException: Parameter count mismatch.

Does anyone know what this means and how to avoid it?

In case anyone asks 'why are you enumerating through the properties of a string', eventually I hope to create a generic class which will output the properties of any type passed to it (which might be a string...).

like image 441
David Avatar asked May 27 '11 19:05

David


3 Answers

System.String has an indexed property that returns the char in the specified location. An indexed property needs an argument (index in this case) therefore the exception.

like image 36
InBetween Avatar answered Nov 13 '22 22:11

InBetween


In this case, one of the string's properties is the indexer for returning the character at the specified location. Thus, when you try to GetValue, the method expects an index but doesn't receive one, causing the exception.

To check which properties require index you can call GetIndexParameters on the PropertyInfo object. It returns an array of ParameterInfo, but you can just check the length of that array (if there are no parameters, it will be zero)

like image 195
Jamie Avatar answered Nov 13 '22 21:11

Jamie


Just as reference... if you want to avoid the TargetParameterCountException when reading properties values:

// Ask each childs to notify also, if any could (if possible)
foreach (PropertyInfo prop in options.GetType().GetProperties())
{
    if (prop.CanRead) // Does the property has a "Get" accessor
    {
        if (prop.GetIndexParameters().Length == 0) // Ensure that the property does not requires any parameter
        {
            var notify = prop.GetValue(options) as INotifyPropertyChanged; 
            if (notify != null)
            {
                notify.PropertyChanged += options.OptionsBasePropertyChanged;
            }
        }
        else
        {
            // Will get TargetParameterCountException if query:
            // var notify = prop.GetValue(options) as INotifyPropertyChanged;
        }
    }
}

Hope it helps ;-)

like image 34
Eric Ouellet Avatar answered Nov 13 '22 21:11

Eric Ouellet