dotnet/wpf · error · ArgumentException
SR.Format(SR.Stylus_IndexOutOfRange…
Error message
SR.Format(SR.Stylus_IndexOutOfRange, index.ToString(System.Globalization.CultureInfo.InvariantCulture))
What it means
TabletDeviceCollection's indexer throws ArgumentException (SR.Stylus_IndexOutOfRange with the index formatted invariantly) when the index is negative or >= Count. Note it throws ArgumentException rather than the more conventional ArgumentOutOfRangeException.
Solutions
- Check index against Count before indexing: if (index >= 0 && index < tablets.Count)
- Iterate with foreach instead of manual indexing
- Re-fetch the collection rather than caching indices across device changes
Example fix
// before
var device = Tablet.TabletDevices[i]; // i may be stale
// after
if (i >= 0 && i < Tablet.TabletDevices.Count)
{
var device = Tablet.TabletDevices[i];
} Defensive patterns
Strategy: try-catch
Validate before calling
if (index < 0 || index >= Tablet.TabletDevices.Count) return null;
Try / catch
try { var device = Tablet.TabletDevices[i]; }
catch (ArgumentException ex) when (ex.Message.Contains("index")) { /* refresh count and retry */ } Prevention
- Prefer foreach over manual indexing
- Re-read Count immediately before indexing; device arrival/removal changes it
When it happens
Trigger: Indexing TabletDeviceCollection with index < 0 or index >= collection Count, e.g. tabletDevices[n] where n came from a count computed elsewhere.
Common situations: Off-by-one loops over tablet devices; caching a count from before a device was unplugged (device count changed between reads); iterating with an index from stale code.
Related errors
AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14).
Data as JSON: /api/errors/e9813aae46e256d0.
Report an issue: GitHub.
Appendix: source
Thrown at src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Input/Stylus/Common/TabletDeviceCollection.cs:73
/// of TabletDevices.
/// </summary>
/// <param name="array">destination array</param>
/// <param name="index">position in destination array to begin copying</param>
public void CopyTo(TabletDevice[] array, int index)
{
TabletDevices.CopyTo(array, index);
}
/// <summary>
/// Retrieve the specified TabletDevice object from the collection.
/// </summary>
/// <param name="index">index of TabletDevice in collection to retrieve</param>
public TabletDevice this[int index]
{
get
{
if (index >= Count || index < 0)
throw new ArgumentException(SR.Format(SR.Stylus_IndexOutOfRange, index.ToString(System.Globalization.CultureInfo.InvariantCulture)), nameof(index));
return TabletDevices[index];
}
}
/// <summary>
/// Returns an object which can be used to lock during synchronization by collection users.
/// <seealso cref="System.Collections.ICollection.SyncRoot"/>
/// </summary>
public object SyncRoot
{
get
{
return this;
}
}
/// <summary>View on GitHub (pinned to 81131a70a4)