The main difference between Foreach and usage
It can even be a simple question, even a school boy can answer.
What are the similarities and differences between "ForEach" and "Using" (asked in interview).
My guess was
1) Both are listed
2) Usage can handle memory resources, but foreach can't.using supports IDisposable, foreach can't.
I want to know the answers.
source to share
Similarities:
- they are both logical extensions of the code, providing boiler table code in other complex scenarios
- both include a hidden variable introduced by the compiler: for an iterator and a snapshot of a disposable, respectively
But that's about where it ends ...
-
using
requiresIDisposable
;foreach
can run fromIEnumerable[<T>]
, but in fact the duck is printed (you don't needIEnumerable
toforeach
) -
using
has the predictable constructiontry
/finally
;foreach
may includeDispose()
if the iterator isIEnumerable<T>
Anyway, I would say that it is using
closer to lock
than to foreach
.
source to share
They both serve completely different purposes.
foreach
is executed to enumerate the items in the collection / array. using
- this is a convenient design so that you properly dispose of what you use. Even if exceptions are thrown eg.
The similarities for these two constructs are simply weird. Can anyone think of any similarities (other than the very obvious, "they are both keywords in C #")?
source to share
The main difference between foreach
and using
is what is foreach
used to enumerate by IEnumerable
, whereas a is using
used to define the scope outside of which the object will be deleted.
There is one similarity between foreach
and using
: enums implement IDisposable
and foreach
will implicitly wrap the use of an enumerator in a block using
. Another way of saying this is that it foreach
can be recoded as a usable block and the resulting IL will be identical.
Code block
var list = new List<int>() {1, 2, 3, 4, 5};
foreach(var i in list) {
Console.WriteLine(i);
}
actually coincides with
var list = new List<int>() {1, 2, 3, 4, 5};
using (var enumerator = list.GetEnumerator()) {
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
source to share