I can write my code in both the ways to achieve my objective, but wondering which one would be the best practice to adhere?
Collection<MyClass> obj = new Collection<MyClass>();
or
IEnumerable<MyClass> obj = new Collection<MyClass>();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In this case,
IEnumerable<MyClass> obj = new Collection<MyClass>()makes no sense at all because you have an empty collection that you cannot add items to (becauseIEnumerabledoes not allow it). How is that useful?Other than that, if we ‘re talking about a local variable that does not get exposed to code outside a method, then the only thing that matters is convenience and clarity. You can max out both of these by using an equivalent of the first form:
If the object is exposed to outside code (e.g. through a property, or if it’s returned by a method) then you should choose the type that makes the best sense given the public interface of your class. This means that as a rule of thumb, you should use the least specialized type possible, and always prefer interfaces.
So if you were exposing
objyou should useIEnumerableif the collection is not meant to be modified by users of your code. Otherwise you should useICollectionif you can; if it’s still not enough thenIList.