I am returning a IList<T> from a method.
In the calling class I want to insert a value at the start of the list/stack.
Inserting a value in List<T> is slower than pushing a value in Stack<T>. But to use stack I need to unbox it.
So the question is which one is better, unbox or using Insert in List<T>? Which one is costlier?
class MyClass
{
}
IList<MyClass> Method1()
{
}
class MainClass
{
List<MyClass> list = (List<MyClass>)Method1();
list.insert(0,new MyClass{...}); //insert at the start.
Stack<MyClass> stack = (Stack<MyClass>)Method1();
stack.Push(new MyClass{...}); //insert at the start
}
You’re not unboxing here in either version (though the first won’t compile.. and the second would always fail at runtime) –
However, in either case, if you do the conversion, it will only work if the actual underlying implementation is that class.
If your method returns an
IList<T>, I’d strongly suggest sticking toIList<T>members. Converting the results to aList<T>orStack<T>(ie: whatever the internal implementation happens to be – which is notStack<T>since that doesn’t implementIList<T>) is very dangerous.The main reason to return
IList<T>is to purposefully allow you to later change the internal implementation.Method1, internally, might later change fromList<T>to some otherIList<T>, which would cause your code to break unexpectedly.That being said, if you know that the internal implementation may be a certain type, you can check for it – but I wouldn’t blindly cast.