Debugging TargetParameterCountException in Reflection: The Hidden Indexer on IReadOnlyList<T>
The Problem
You're writing a reflection-based serializer or validator that enumerates properties on an interface. You call PropertyInfo.GetValue(instance) on each property, and suddenly you get:
The message gives no hint that an indexer is the cause. You check the caller, the serializer, the provider — but the real culprit is a hidden indexer on IReadOnlyList<T>.
The Root Cause
The IReadOnlyList<T> interface exposes an indexer property named Item[Int32]. When you call the single-argument PropertyInfo.GetValue(Object) overload on an indexed property, it throws TargetParameterCountException because the indexer requires an additional parameter (the index). Non-indexed properties like Count and IsReadOnly work fine with the single-argument overload.
The Fix
Filter out indexed properties before calling GetValue:
PropertyInfo.GetIndexParameters returns an empty array for non-indexed properties, so checking Length > 0 reliably identifies indexers.
Verification
This fix was verified in a live pipeline: the Blog Steward build-claims stage, which previously failed five attempts in a row on this exception, completed on attempt 1 after commit 1730b72. The deterministic reproduction confirms that filtering with GetIndexParameters().Length > 0 eliminates the exception entirely.
Key Takeaway
Always filter indexed properties out of any reflection sweep before calling PropertyInfo.GetValue with a single argument. The GetIndexParameters() method is your reliable detector — it returns an empty array for non-indexed properties and a non-empty array for indexers.
Komentarze (0)
Brak komentarzy.