Question

This could even be a simple question even a school boy can answer.

What is the similarities and differences between "ForEach" and "Using" (asked in an interview).

My assumption was

1)Both are enumerable

2) Using can handle memory resources,but foreach can't.using supports IDisposable,foreach can't.

I wish to know the answers.

Was it helpful?

Solution

Similarities:

  • they are both logical code expansions, providing boiler-plate code of otherwise complex scenarios
  • both involve a hidden variable introduced by the compiler: for the iterator and the snapshot of the disposable object, respectively

But that is about where it ends...

  • using demands IDisposable; foreach might trigger from IEnumerable[<T>], but is actually duck typed (you don't need IEnumerable for foreach)
  • using has a predictable try/finally construct; foreach might involve a Dispose() if the iterator is IEnumerable<T>

If anything, I'd say using is closer to lock than to foreach.

OTHER TIPS

  1. Nope
  2. Nope, foreach will dispose of your IEnumerable if it implements IDisposable.

using defines a scope, outside of which an object or objects will be disposed. It does not loop or iterate.

They both serve very different purposes.

foreach is made for enumerating items in a collection/array. using is a handy construction for making sure that you properly dispose of the thing your using. Even when exceptions are thrown for example.

Similarities for these two constructs are just, weird. Can anyone think of any similarities (apart from the very obvious: 'they are both keywords in C#')?

The main difference between foreach and using is that foreach is used for enumerating over an IEnumerable whereas a using is used for defining a scope outside of which an object will be disposed.

There is one similarity between foreach and using: Enumerators implement IDisposable and a foreach will implicitly wrap the use of an enumerator in a using block. Another way of saying this is that is that a foreach can be recoded as a using block and the resulting IL will be identical.

The code block

var list = new List<int>() {1, 2, 3, 4, 5};
foreach(var i in list) {
    Console.WriteLine(i);
}

is effectively the same as

var list = new List<int>() {1, 2, 3, 4, 5};
using (var enumerator = list.GetEnumerator()) {
    while (enumerator.MoveNext()) {
        Console.WriteLine(enumerator.Current);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top