Debugging TargetParameterCountException in .NET: hidden indexer in IReadOnlyList<T>
Problem
You are writing a reflection-based serializer or validator that enumerates interface properties. You call PropertyInfo.GetValue(instance) on each property and suddenly get:
System.Reflection.TargetParameterCountException: Parameter count mismatchThe message gives no hint that an indexer is the cause. You check the caller, serializer, provider — but the real culprit is a hidden indexer in IReadOnlyList<T>.
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 such as Count and IsReadOnly work correctly with the single-argument overload.
Solution
Filter out indexed properties before calling GetValue:
var properties = typeof(IReadOnlyList<string>).GetProperties()
.Where(p => p.GetIndexParameters().Length == 0);
foreach (var property in properties)
{
var value = property.GetValue(listInstance);
// Works for Count, IsReadOnly; skips Item[Int32]
}PropertyInfo.GetIndexParameters returns an empty array for non-indexed properties, so checking Length > 0 reliably identifies indexers.
Verification
This fix was verified in a production pipeline: the build-claims stage in Blog Steward, which had previously failed five times in a row with this exception, passed on the first attempt after commit 1730b72. A deterministic reproduction confirms that filtering with GetIndexParameters().Length > 0 completely eliminates the exception.
Key takeaway
Always filter indexed properties out of any reflection pass before calling PropertyInfo.GetValue with a single argument. The GetIndexParameters() method is a reliable detector — it returns an empty array for non-indexed properties and a non-empty one for indexers.
Comments (0)
No comments yet.
Add a comment
Comments are published after moderation. Your e-mail address stays private.