Code inspection: Cast expression can be replaced with simplified type arguments
This inspection suggests making type conversions safer and clearer by specifying the type argument directly rather than casting within a lambda expression.
In the example below, there are several issues with casting obj
within a lambda expression: it can potentially hide type conversion issues, it makes the code harder to read and understand, the type argument T
in DoWork<T>()
can be inferred by the compiler, making the cast unnecessary.
To avoid these issues, you can get rid of the cast and specify the type argument directly at the method call.
public interface IBase;
public class Derived : IBase;
public class Sample
{
void Test(IEnumerable<Derived> obj)
{
DoWork(() => (IEnumerable<IBase>) obj);
}
void DoWork<T>(Func<IEnumerable<T>> action) { /*...*/ }
}
public interface IBase;
public class Derived : IBase;
public class Sample
{
void Test(IEnumerable<Derived> obj)
{
DoWork<IBase>(() => obj);
}
void DoWork<T>(Func<IEnumerable<T>> action) { /*...*/ }
}
Last modified: 09 August 2024