Created
May 4, 2021 08:32
-
-
Save kolosovpetro/e31f26324376fde0d0054abd7714d353 to your computer and use it in GitHub Desktop.
ducktypes_disposablle.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| namespace ConsoleApp1 | |
| { | |
| public class CustomEnumerable | |
| { | |
| public class CustomEnumerator : IDisposable | |
| { | |
| private readonly CustomEnumerable _enumerable; | |
| private int _index = -1; | |
| public CustomEnumerator(CustomEnumerable enumerable) => _enumerable = enumerable; | |
| private IList<string> Items => _enumerable._items; | |
| public string Current => _index >= 0 ? Items[_index] : null; | |
| public bool MoveNext() | |
| { | |
| if (_index >= Items.Count - 1) return false; | |
| _index++; | |
| return true; | |
| } | |
| public void Dispose() | |
| { | |
| Console.WriteLine("Disposed"); | |
| } | |
| } | |
| private readonly IList<string> _items; | |
| public CustomEnumerable(params string[] items) => _items = new List<string>(items); | |
| public CustomEnumerator GetEnumerator() => new CustomEnumerator(this); | |
| } | |
| public class C | |
| { | |
| public static void Main() | |
| { | |
| var enumerable = new CustomEnumerable("One", "Two", "Three"); | |
| foreach (string item in enumerable) | |
| { | |
| Console.WriteLine(item); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment