Quantcast
Channel: YouTrackReSharper (RSRP) - Bug and Issue Tracker
Viewing all articles
Browse latest Browse all 106942

RSRP-288523: Suggesting OfType on generic collections

$
0
0
Reporter Mauricio Scheffer (mausch) Mauricio Scheffer (mausch)
Created Feb 24, 2012 9:58:59 PM
Updated Apr 3, 2012 5:48:28 PM
Priority Normal
Type Unspecified
Fix versions No Fix versions
State Open
Assignee Evgeny Pasynkov (pasynkov)
Subsystem No subsystem
Affected versions 6.1.1
Fixed in build No Fixed in build
Given this code:

IEnumerable<Stream> streams = new Stream[] {new MemoryStream(), new BufferedStream(new MemoryStream()), };
var memoryStreams = streams.Where(x => x is MemoryStream).Select(x => (MemoryStream) x);


ReSharper 6.1.42.60 suggests replacing the second line with OfType<T>:

var memoryStreams = streams.OfType<MemoryStream>();


Now replace the definition of 'streams' with:

IEnumerable<string> streams = new[] {""};


The code with OfType compiles successfully, even though it's clearly incorrect. The original code wouldn't have compiled, the cast from string to MemoryStream fails at compile-time.

In more general terms, under these conditions:

IEnumerable<Supertype> x
x.Where(x => x is Subtype).Select(x => (Subtype) x)


ReSharper shouldn't recommend replacing with x.OfType<Subtype>()

Even more generally, ReSharper should never recommend applying OfType<T> to an IEnumerable<U> when U != object.
It should offer to convert code away from OfType<T> when it sees it being applied to an IEnumerable<U>, either to the original code posted here or:

streams.Select(x => x as MemoryStream).Where(x => x != null);


which is also type-safe and a bit less verbose.

Related: RSRP-288411 , RSRP-288336

Viewing all articles
Browse latest Browse all 106942

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>