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>();
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>();
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 (because IEnumerable
does 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:
var obj = new Collection<MyClass>();
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 obj
you should use IEnumerable
if the collection is not meant to be modified by users of your code. Otherwise you should use ICollection
if you can; if it's still not enough then IList
.
Personally, I prefer
var obj = new Collection<MyClass>();
This compiles successfully even to .NET 2.0 with VS.NET 2008 and above.
Personally I think it depends and it depends on the level of specificity that you want to achieve.
Bare in mind that Collection<T>
impliments IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
.
As Jon already pointed out, the example you've given doesn't make any sense because you're creating an empty collection you cannot add to but given a different example the level of specificity comes into play.
Collection has a specific set of members and if those members are required, use it. If you want to be less specific about the data in the collection you can cast to any of the interfaces implimented by Collectioin. The question is, why would you want to if you're creating a Collection<T>
.
It totaly depends on requirement. If delaling with DAL or returning database object, then IEnumerable is preferable.
Declaring as Collection will give more functionality to add. You can get more idea on there.