You have recently created a custom collection class named ShoppingList for a local supermarket.
This custom class will include ShoppinItem objects that have the public properties listed below.
* Name
* AisleNumber
* OnDiscount
You are required to enable users of your class to iterate through the ShoppingList collection, and to list each product name and aisle number using the foreach statement.
You need to achieve this by declaring the appropriate code.
What code should you use?
A.
public class ShoppingList : ICollection {
// Class implementation
}
B.
public class ShoppingList : IEnumerator, IEnumerable{
// Class implementation
}
C.
public class ShoppingList : Ilist{
// Class implementation
}
D.
public class ShoppingList : Enum {
// Class implementation
}
Explanation:
You should implement the IEnumerable and IEnumerator interfaces of the System.Collections namespace to ensure that your collection class supports foreach iteration. The IEnumerable interface defines only one method named GetEnumerator that returns an object of type IEnumerator of the
System.Collections namespace and is used to support iteration over a collection. The IEnumerator interface supports methods, such as Current, MoveNext, and Reset to iterate through a collection. The Current method returns the current element of the collection. The Move method positions the enumerator to the next available element of the collection. The Reset method positions the enumerator before the first element of the collection.
Incorrect Answers:
A: You should not use the code that implements the ICollection interface because this interface is used to define properties in a collection. Implementing this interface will not ensure that your collection class supports foreach iteration because it does not inherit the IEnumerator interface.
C: You should not use the code that implements the Ilist interface because this interface is used to define properties of a non-generic list of items accessed by index. Implementing this interface will not ensure that your collection class supports foreach iteration because it does not inherit the IEnumerator interface.
D: You should not use the code that inherits the Enum because this structure is used
I agree with the answer. B