Reputation: 1620
I know that IEnumerable is an interface, and I also know that when a class implements an interface it has to implement specific bodies for the methods in that interface. I've been writing a program recently and I felt that I need to implement the Ienumerable to one of my class so as to allow it to be used in a foreach loop. After I did so which is done this way:
class FData: IEnumerable<EClass> {
// Removed the irrelevant contents
public IEnumerator<EnumerableClass> GetEnumerator()
{
for (int i = 0; i < Emp_Id.Count; i++) {
yield return (new EnumerableClass { Emp_Id = Emp_Id[i], Salary = Salary[i] });
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
I see that my FData class can be used exactly like a List as if it is inheriting all the enumerable methods such as Select(), All(), Any() ,etc.
I'd like to know how exactly does this happen if the behavior of these method are not defined in the interface ?
Upvotes: 0
Views: 103
Reputation: 22153
They are extension methods and here's some more info.
Extension methods exist as static methods within static classes within some namespace and the first argument of the method includes the this
keyword (see the example method signature below of OfType
). In this case you are probably seeing the System.Linq.Enumerable extension methods. If you were to remove the using System.Linq
namespace from your class file those extension methods would no longer be available. After market refactoring tools like Resharper will suggest extension methods where appropriate, but what you get out of the box in Visual Studio will not suggest extension methods (e.g. Ctrl+.). Therefore, if you want them you must make sure to add an appropriate using
statement at the top of your class file. If you do not want them and do not need any other class in the namespace you can remove it and the extension methods will no longer be available.
public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source);
The beauty of this is that anything that implements IEnumerable
will have the OfType
method available so long as the namespace of that extension method is included. You can also make your own extension methods.
Upvotes: 2
Reputation: 53958
All these methods are extension
methods for types that implement the IEnumerable
interface. So once a type implements IEnumerable
has as methods also these methods - except the methods, that have been already defined inside the body of your type.
For further documentation, please have a look here. Also, if you haven't before heard about extension
methods, please first have a look here.
Upvotes: 7