Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redundant 'IEnumerable.OfType<T>' call consider comparing with 'null' instead

Tags:

c#

resharper

I'm getting this message from ReSharper. ReSharper is not proposing the change that I think would be appropriate after examining the code. As a result I am concerned that the problem might might be my not understanding what's going on instead of ReSharper not being as helpful as it could be.

public interface IFrobable { }

public class DataClass
{  
    public List<IFrobable> Frobables {get; set;}

    //...
}


public class WorkerClass
{
    //...

    void Frobinate(List<IFrobable> frobables)
    { 
       //Frobs the input
    }

    void DoSomething(List<IFrobable> input>)
    {
        //Original code with Resharper on OfType<IActivity>
        Frobinate(input.OfType<IFrobable>().ToList()); 

        //Suggested change from ReSharper - Is this a generic refactor 
        //instead of issue specific?
        Frobinate(Enumerable.OfType<IFrobable>(input).ToList()); 

        //What I think should be safe to do - compiles and appears to work
        Frobinate(input);
    }
}

Is there any reason why my proposed change might not be safe.

like image 849
Dan Is Fiddling By Firelight Avatar asked Oct 24 '25 00:10

Dan Is Fiddling By Firelight


2 Answers

This is a regular function call:

Enumerable.OfType<IFrobable>(input)

This is the same function but invoked as an extension method:

input.OfType<IFrobable>()

In your case:

Frobinate(input);

Is absolutely fine because:

input.OfType<IFrobable>().ToList()

Equals to:

input.Where(x => x as IFrobable != null).ToList()

And in you method input is already defined as List<IFrobable> so what's the point?

like image 90
gdoron is supporting Monica Avatar answered Oct 27 '25 03:10

gdoron is supporting Monica


Your last case may or may not introduce a logic error.

Do you really want Frobinate the ability to modify the input list passed into DoSomething or just a copy of those references?

like image 41
Daniel A. White Avatar answered Oct 27 '25 03:10

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!