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.

+2


source to share


5 answers


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

    requires IDisposable

    ; foreach

    can run from IEnumerable[<T>]

    , but in fact the duck is printed (you don't need IEnumerable

    to foreach

    )
  • using

    has the predictable construction try

    / finally

    ; foreach

    may include Dispose()

    if the iterator isIEnumerable<T>

Anyway, I would say that it is using

closer to lock

than to foreach

.

+3


source


  • Nope
  • No, foreach

    will dispose of yours IEnumerable

    if it implements IDisposable

    .


+8


source


using

defines the area outside which the object or objects will be removed. It doesn't loop or repeat itself.

+4


source


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 #")?

+4


source


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);
    }
}

      

+3


source







All Articles