Code inspection: Possible 'System.InvalidCastException'
This inspection reports an explicit cast that can fail at runtime with InvalidCastException.
Example
using System;
static void Handle(object value)
{
if (value is Action<string>)
{
var action = (Action<int>)value;
}
}
The type check proves that value is Action<string>, so casting it to Action<int> is not safe.
How to fix it
There is no dedicated quick-fix for this inspection. A typical fix is to cast to the type you actually checked for, or use pattern matching.
using System;
static void Handle(object value)
{
if (value is Action<string> action)
{
action("text");
}
}
01 April 2026