Custom collections - how we are able to get foreach and linq features without implementing any methods ?

YottaBot

New member
Joined
Aug 8, 2021
Messages
1
Programming Experience
3-5
Using a custom class Customer.
I have not implemented iEumerable.
Also i have not overridden the methods MoveNext(), Reset() of iEnumerator.

But i am able to use foreach to iterate through customers collection. And able to query using linq where clause.

I am not able to understand how we are able to get these foreach and linq features without implementing any methods in the below example.

Please help me to understand how this works.

C#:
public class Customer
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string Mobile { get; set; }

    }


// in main method
Customer[] customers = new Customer[]
            {
                new Customer {Name="Raj Kumar", City="Bangalore", Mobile="9599999123"},
                new Customer { Name = "Sudhir Wadje", City = "Bhubaneswar", Mobile = "9488888321" },
                new Customer { Name = "Anil", City = "Delhi", Mobile = "8077777987" }
            };


IEnumerable<Customer> result = from cust in customers where (cust.City.StartsWith("B")) select cust;
foreach (Customer customer in result)
{
           Console.WriteLine(customer.City);
            }
 
Last edited by a moderator:
That works because the you have an array of Customer. The .NET Framework Array class implements IEnumerable.

Try using LINQ on a single Customer instance, and you'll see that it fails because your custom class doesn't expose the appropriate interface(s).
 
For the record, LINQ is based on IEnumerable<T> rather than just IEnumerable. That's why you need the Cast<T> method to get an IEnumerable<T> from an IEnumerable in order to call any other LINQ method. Interestingly, while the documentation states that the Array class implements IEnumerable but not that it implements IEnumerable<T>, an instance of the Array class or a conventionally created array object both implement both interfaces.
C#:
var arr1 = Array.CreateInstance(typeof(int), 10);
var arr2 = new int[10];

Console.WriteLine(arr1 is IEnumerable);
Console.WriteLine(arr1 is IEnumerable<int>);
Console.WriteLine(arr2 is IEnumerable);
Console.WriteLine(arr2 is IEnumerable<int>);
All four lines of that code display "True".

As suggested, you're actually performing your LINQ query on the array, not the elements of the array. It's just like you perform a database query on a table, not a record in the table. How would actions like filtering and sorting make sense unless the thing you were querying contained multiple records/items?
 
Back
Top Bottom