开发者

Major difference between Foreach and Using

开发者 https://www.devze.com 2022-12-09 08:21 出处:网络
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).

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.


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号