What is the best calling approach for Dispose()sequence elements?
Suppose something like:
IEnumerable<string> locations = ...
var streams = locations.Select ( a => new FileStream ( a , FileMode.Open ) );
var notEmptyStreams = streams.Where ( a => a.Length > 0 );
var firstBytes = notEmptyStreams.Select ( a => a.ReadByte () );
var average = firstBytes.Average ();
How do you place instances FileStream(as soon as they are no longer needed) while saving compressed code?
To clarify: this is not an actual piece of code, these lines are methods in a set of classes, and the type is FileStreamalso just an example.
Performs something line by line:
public static IEnumerable<TSource> Where<TSource> (
this IEnumerable<TSource> source ,
Func<TSource , bool> predicate
)
where TSource : IDisposable {
foreach ( var item in source ) {
if ( predicate ( item ) ) {
yield return item;
}
else {
item.Dispose ();
}
}
}
might be a good idea?
Alternatively: do you always solve a very specific scenario with respect IEnumerable<IDisposable>, without trying to generalize? Is this because, if this is not a typical situation? Do you design around it first? If so, how?