HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Is ToIEnumerable<T> good practice?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
practicetoienumerablegood

Problem

I have an extension method that does this:

public static IEnumerable ToIEnumerable(this T source) where T : new()
{
    return new[] { source };
}


I need to be able to convert any object to an IEnumerable.

For example when I use the .NET Except method:

public static IEnumerable Except(this IEnumerable first)


I can call Except by doing the following:

return objects.Except(this.ToIEnumerable());


Is ToIEnumerable good practice or should I solve the problem in differently?

Solution

While I don't see why ToIEnumerable is bad practice, in this specific case I think it is. You're comparing with only one object; why not just attach a where clause on to things? I.e.

return objects.Where((other) => other != this);


or possibly

return objects.Where((other) => !Object.ReferenceEquals(other, this));


Not only will this perform better than Except here, but it's easier to understand, and avoids the entire ToIEnumerable thing entirely.

Code Snippets

return objects.Where((other) => other != this);
return objects.Where((other) => !Object.ReferenceEquals(other, this));

Context

StackExchange Code Review Q#836, answer score: 7

Revisions (0)

No revisions yet.