Search Results

Search found 102 results on 5 pages for 'ienumerator'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • IEnumerator.Current property and IEnumerator.MoveNext method

    - by nmarun
    Here’s a question: What happens to the Current property of an IEnumerator before and after the MoveNext() call? When I say ‘after the MoveNext() call’, I mean after MoveNext() returns a false indicating an end of the collection. I was going through the MSDN for IEnumerator.Current and the first paragraph basically boils down to: If MoveNext() method has never been called on an IEnumerator, the Current property is undefined. I wanted to know what ‘undefined’ means – is it null? If so, what if the...(read more)

    Read the article

  • Return an empty IEnumerator

    - by Rekreativc
    Hello! I have an interface that, among other things, implements a "public IEnumerator GetEnumerator()" method, so I can use the interface in a foreach statement. I implement this interface in several classes and in one of them, I want to return an empty IEnumerator. Right now I do this the following way: public IEnumerator GetEnumerator() { ArrayList arr = new ArrayList(); return arr.GetEnumerator(); } However I consider this an ugly hack, and I can't help but think that there is a better way of returning an empty IEnumerator. Is there?

    Read the article

  • [C#] Problems with implementing generic IEnumerator and IComparable

    - by r0h
    Hi all! I'm working on an AVL Tree. The tree itself seems to be working but I need a iterator to walk through the values of the tree. Therefore I tried to implement the IEnumerator interace. Unfortunately I get a compile time error implementing IEnumerator and IComparable. First the code and below that the error. class AvlTreePreOrderEnumerator<T> : IEnumerator<T> where T :IComparable<T> { private AvlTreeNode<T> current = default(T); private AvlTreeNode<T> tree = null; private Queue<AvlTreeNode<T>> traverseQueue = null; public AvlTreePreOrderEnumerator(AvlTreeNode<T> tree) { this.tree = tree; //Build queue traverseQueue = new Queue<AvlTreeNode<T>>(); visitNode(this.tree.Root); } private void visitNode(AvlTreeNode<T> node) { if (node == null) return; else { traverseQueue.Enqueue(node); visitNode(node.LeftChild); visitNode(node.RightChild); } } public T Current { get { return current.Value; } } object IEnumerator.Current { get { return Current; } } public void Dispose() { current = null; tree = null; } public void Reset() { current = null; } public bool MoveNext() { if (traverseQueue.Count > 0) current = traverseQueue.Dequeue(); else current = null; return (current != null); } } The error given by VS2008: Error 1 The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Opdr2_AvlTreeTest_Final.AvlTreeNode'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable'. For now I've not included the tree and node logic. I anybody thinks is necessary to resolve this probleem, just say so! Thx!

    Read the article

  • Why in this example (got from msdn), in GetEnumerator method , new PeopleEnum returns IEnumerator?

    - by odiseh
    Hi guys, Why in this example (got from msdn), in GetEnumerator method , PeopleEnum returns IEnumerator? public class Person { public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } public string firstName; public string lastName; } public class People : IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } } //why??? IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) GetEnumerator(); } public PeopleEnum GetEnumerator() { return new PeopleEnum(_people); } } public class PeopleEnum : IEnumerator { public Person[] _people; // Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public PeopleEnum(Person[] list) { _people = list; } public bool MoveNext() { position++; return (position < _people.Length); } public void Reset() { position = -1; } object IEnumerator.Current { get { return Current; } } public Person Current { get { try { return _people[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } }

    Read the article

  • IEnumerable and IEnumerator in the same class, bad idea?

    - by David Rutten
    Is this a bad idea? Private Class GH_DataStructureEnumerator(Of Q As Types.IGH_Goo) Implements IEnumerable(Of Q) Implements IEnumerator(Of Q) .... .... 'Current, MoveNext, Reset etc.' .... .... Public Function GetEnumerator_Generic() As IEnumerator(Of Q) _ Implements IEnumerable(Of Q).GetEnumerator Return Me End Function End Class This class is only visible as an IEnumerable(Of T) readonly property, and it saves me an additional class that wraps IEnumerator(Of T). But somehow it just seems wrong. Is there a better way?

    Read the article

  • IEnumerator: Is it normal to have an empty Dispose method?

    - by C. Ross
    I'm writing an IEnumerator<T> class to iterate over a COM collection I'm wrappering. I've noticed that IEnumerator<T> extends IDisposable, so I'm required to implement the Dispose method. However, I can't think of anything I would put there, as I only have a reference to the collection (which I wouldn't want being disposed at the end of a foreach), and an int for the index. Is it normal to leave the Dispose method empty?

    Read the article

  • Synchronized IEnumerator<T>

    - by Dan Bryant
    I'm putting together a custom SynchronizedCollection<T> class so that I can have a synchronized Observable collection for my WPF application. The synchronization is provided via a ReaderWriterLockSlim, which, for the most part, has been easy to apply. The case I'm having trouble with is how to provide thread-safe enumeration of the collection. I've created a custom IEnumerator<T> nested class that looks like this: private class SynchronizedEnumerator : IEnumerator<T> { private SynchronizedCollection<T> _collection; private int _currentIndex; internal SynchronizedEnumerator(SynchronizedCollection<T> collection) { _collection = collection; _collection._lock.EnterReadLock(); _currentIndex = -1; } #region IEnumerator<T> Members public T Current { get; private set;} #endregion #region IDisposable Members public void Dispose() { var collection = _collection; if (collection != null) collection._lock.ExitReadLock(); _collection = null; } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { var collection = _collection; if (collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex++; if (_currentIndex >= collection.Count) { Current = default(T); return false; } Current = collection[_currentIndex]; return true; } public void Reset() { if (_collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex = -1; Current = default(T); } #endregion } My concern, however, is that if the Enumerator is not Disposed, the lock will never be released. In most use cases, this is not a problem, as foreach should properly call Dispose. It could be a problem, however, if a consumer retrieves an explicit Enumerator instance. Is my only option to document the class with a caveat implementer reminding the consumer to call Dispose if using the Enumerator explicitly or is there a way to safely release the lock during finalization? I'm thinking not, since the finalizer doesn't even run on the same thread, but I was curious if there other ways to improve this. EDIT After thinking about this a bit and reading the responses (particular thanks to Hans), I've decided this is definitely a bad idea. The biggest issue actually isn't forgetting to Dispose, but rather a leisurely consumer creating deadlock while enumerating. I now only read-lock long enough to get a copy and return the enumerator for the copy.

    Read the article

  • IEnumerator seems to be effecting all objects, and not one at a time

    - by PFranchise
    Hey, I am trying to alter an attribute of an object. I am setting it to the value of that same attribute stored on another table. There is a one to many relationship between the two. The product end is the one and the versions is the many. Right now, both these methods that I have tried have set all the products returned equal to the final version object. So, in this case they are all the same. I am not sure where the issue lies. Here are my two code snipets, both yield the same result. int x = 1 IEnumerator<Product> ie = productQuery.GetEnumerator(); while (ie.MoveNext()) { ie.Current.RSTATE = ie.Current.Versions.First(o => o.VersionNumber == x).RSTATE; x++; } and foreach (var product in productQuery) { product.RSTATE = product.Versions.Single(o => o.VersionNumber == x).RSTATE; x++; } The versions table holds information for previous products, each is distinguished by the version number. I know that it will start at 1 and go until it reaches the current version, based on my query returning the proper number of products. Thanks for any advice.

    Read the article

  • How to Implement an Interface that Requires Duplicate Member Names?

    - by Will Marcouiller
    I often have to implement some interfaces such as IEnumerable<T> in my code. Each time, when implementing automatically, I encounter the following: public IEnumerator<T> GetEnumerator() { // Code here... } public IEnumerator GetEnumerator1() { // Code here... } Though I have to implement both GetEnumerator() methods, they impossibly can have the same name, even if we understand that they do the same, somehow. The compiler can't treat them as one being the overload of the other, because only the return type differs. When doing so, I manage to set the GetEnumerator1() accessor to private. This way, the compiler doesn't complaint about not implementing the interface member, and I simply throw a NotImplementedException within the method's body. However, I wonder whether it is a good practice, or if I shall proceed differently, as perhaps a method alias or something like so. What is the best approach while implementing an interface such as IEnumerable<T> that requires the implementation of two different methods with the same name? EDIT #1 Does VB.NET reacts differently from C# while implementing interfaces, since in VB.NET it is explicitly implemented, thus forcing the GetEnumerator1(). Here's the code: Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator // Code here... End Function Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator Implements System.Collections.Generic.IEnumerable.GetEnumerator // Code here... End Function Both GetEnumerator() methods are explicitly implemented, and the compile will refuse them to have the same name. Why?

    Read the article

  • IEnumerable<T> representing the "rest" of an IEnumerable<T> sequence

    - by Henry Jackson
    If I am walking through an IEnumerable<T>, is there any way to get a new IEnumerable<T> representing the remaining items after the current one. For example, I would like to write an extension method IEnumerator<T>.Remaining(): IEnumerable<int> sequence = ... IEnumerator<int> enumerator = sequence.GetEnumerator(); if (enumerator.MoveNext() && enumerator.MoveNext()) { IEnumerable<int> rest = enumerator.Remaining(); // 'rest' would contain elements in 'sequence' start at the 3rd element } I'm thinking of the collection of a sort of singly-linked list, so there should be a way to represent any remaining elements, right? I don't see any way to do this exposed on either IEnumerable<T> or IEnumerator<T>, so maybe it's incompatible with the notion of a potentially unbounded, nondeterministic sequence of elements.

    Read the article

  • How to Implement an Interface that Requires Duplicate Member Names in C#?

    - by Will Marcouiller
    I often have to implement some interfaces such as IEnumerable<T> in my code. Each time, when implementing automatically, I encounter the following: public IEnumerator<T> GetEnumerator() { // Code here... } public IEnumerator GetEnumerator1() { // Code here... } Though I have to implement both GetEnumerator() methods, they impossibly can have the same name, even if we understand that they do the same, somehow. The compiler can't treat them as one being the overload of the other, because only the return type differs. When doing so, I manage to set the GetEnumerator1() accessor to private. This way, the compiler doesn't complaint about not implementing the interface member, and I simply throw a NotImplementedException within the methods body. However, I wonder whether it is a good practice, or if I shall proceed differently, as perhaps a method alias or something like so. What is the best approach while implementing an interface such as IEnumerable<T> that requires the implementation of two different methods with the same name?

    Read the article

  • Why enumerator structs are a really bad idea (redux)

    - by Simon Cooper
    My previous blog post went into some detail as to why calling MoveNext on a BCL generic collection enumerator didn't quite do what you thought it would. This post covers the Reset method. To recap, here's the simple wrapper around a linked list enumerator struct from my previous post (minus the readonly on the enumerator variable): sealed class EnumeratorWrapper : IEnumerator<int> { private LinkedList<int>.Enumerator m_Enumerator; public EnumeratorWrapper(LinkedList<int> linkedList) { m_Enumerator = linkedList.GetEnumerator(); } public int Current { get { return m_Enumerator.Current; } } object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { return m_Enumerator.MoveNext(); } public void Reset() { ((System.Collections.IEnumerator)m_Enumerator).Reset(); } public void Dispose() { m_Enumerator.Dispose(); } } If you have a look at the Reset method, you'll notice I'm having to cast to IEnumerator to be able to call Reset on m_Enumerator. This is because the implementation of LinkedList<int>.Enumerator.Reset, and indeed of all the other Reset methods on the BCL generic collection enumerators, is an explicit interface implementation. However, IEnumerator is a reference type. LinkedList<int>.Enumerator is a value type. That means, in order to call the reset method at all, the enumerator has to be boxed. And the IL confirms this: .method public hidebysig newslot virtual final instance void Reset() cil managed { .maxstack 8 L_0000: nop L_0001: ldarg.0 L_0002: ldfld valuetype [System]System.Collections.Generic.LinkedList`1/Enumerator<int32> EnumeratorWrapper::m_Enumerator L_0007: box [System]System.Collections.Generic.LinkedList`1/Enumerator<int32> L_000c: callvirt instance void [mscorlib]System.Collections.IEnumerator::Reset() L_0011: nop L_0012: ret } On line 0007, we're doing a box operation, which copies the enumerator to a reference object on the heap, then on line 000c calling Reset on this boxed object. So m_Enumerator in the wrapper class is not modified by the call the Reset. And this is the only way to call the Reset method on this variable (without using reflection). Therefore, the only way that the collection enumerator struct can be used safely is to store them as a boxed IEnumerator<T>, and not use them as value types at all.

    Read the article

  • NullReferenceException when changing skin/theme via Application.Current.Resources

    - by CoolCat
    I am writing an wpf application with multiple skins. The code to switch theme is as below: try { Application.Current.Resources.MergedDictionaries.Add( resource ); } catch( Exception ex ) { } The first time the code is called (to switch to a new theme), it is executed successfully; however, any subsequent calls to the same code would throw System.NullReferenceException. The way I set up my themes are similar to what described here: http://www.codewrecks.com/blog/index.php/2008/05/22/simple-skinnable-and-theme-management-in-wpf-user-interface/. Has anyone seen this error before? How do I go about debugging this since the exception is thrown else where? Any help is greatly appreciated. StackTrace: at System.Windows.EffectiveValueEntry.GetFlattenedEntry(RequestFlags requests) at System.Windows.DependencyObject.EvaluateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry newEntry, OperationType operationType) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType) at System.Windows.StyleHelper.ApplyStyleOrTemplateValue(FrameworkObject fo, DependencyProperty dp) at System.Windows.StyleHelper.InvalidateContainerDependents(DependencyObject container, FrugalStructList`1& exclusionContainerDependents, FrugalStructList`1& oldContainerDependents, FrugalStructList`1& newContainerDependents) at System.Windows.StyleHelper.DoStyleInvalidations(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle) at System.Windows.StyleHelper.UpdateStyleCache(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle, Style& styleCache) at System.Windows.FrameworkElement.OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType) at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp) at System.Windows.FrameworkElement.UpdateStyleProperty() at System.Windows.TreeWalkHelper.InvalidateStyleAndReferences(DependencyObject d, ResourcesChangeInfo info, Boolean containsTypeOfKey) at System.Windows.TreeWalkHelper.OnResourcesChanged(DependencyObject d, ResourcesChangeInfo info, Boolean raiseResourceChangedEvent) at System.Windows.TreeWalkHelper.OnResourcesChangedCallback(DependencyObject d, ResourcesChangeInfo info) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1.StartWalk(DependencyObject startNode, Boolean skipStartNode) at System.Windows.TreeWalkHelper.InvalidateOnResourcesChange(FrameworkElement fe, FrameworkContentElement fce, ResourcesChangeInfo info) at System.Windows.Application.InvalidateResourceReferenceOnWindowCollection(WindowCollection wc, ResourcesChangeInfo info) at System.Windows.ResourceDictionary.NotifyOwners(ResourcesChangeInfo info) at System.Windows.ResourceDictionary.OnMergedDictionariesChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at System.Windows.ResourceDictionaryCollection.InsertItem(Int32 index, ResourceDictionary item) at System.Collections.ObjectModel.Collection`1.Add(T item)

    Read the article

  • WPF UserControl Style results in error message

    - by Didier
    Hi I'm new in WPF so I try to create a WPF UserControl. My problem is about the style of the user control I've Created. On a design time I got this error message Can only base on a Style with target type that is base type 'RichTextBox'. at System.Windows.Style.Seal() at System.Windows.StyleHelper.UpdateStyleCache(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle, Style& styleCache) at System.Windows.FrameworkElement.OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType) at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp) at System.Windows.FrameworkElement.UpdateStyleProperty() at System.Windows.TreeWalkHelper.InvalidateStyleAndReferences(DependencyObject d, ResourcesChangeInfo info, Boolean containsTypeOfKey) at System.Windows.TreeWalkHelper.OnResourcesChanged(DependencyObject d, ResourcesChangeInfo info, Boolean raiseResourceChangedEvent) at System.Windows.TreeWalkHelper.OnResourcesChangedCallback(DependencyObject d, ResourcesChangeInfo info) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1.StartWalk(DependencyObject startNode, Boolean skipStartNode) at System.Windows.TreeWalkHelper.InvalidateOnResourcesChange(FrameworkElement fe, FrameworkContentElement fce, ResourcesChangeInfo info) at System.Windows.ResourceDictionary.NotifyOwners(ResourcesChangeInfo info) at System.Windows.ResourceDictionary.EndInit() at MS.Internal.Host.Designer.OnAppResourcesChanged(Object sender, EventArgs e) at MS.Internal.Host.Designer.get_View() at MS.Internal.Designer.VSDesigner.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedView.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedDesignerFactory.Load(IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.Load() at MS.Internal.Designer.DesignerPane.LoadDesignerView() And at a run time An error Message type XamlParseException Occurs and the message is: Cannot create instance of 'RichTextBox' defined in assembly 'PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Can only base on a Style with target type that is base type 'RichTextBox'. Error at object 'System.Windows.Controls.Grid' in markup file 'NameSpace;component/usercontrols /myusercontrol.xaml' Line 125 Position 14. My user control have 3 richtextboxes 1 textbox and 3 dropdownlist and about 10 buttons. I think The problem is about to define the style of my user control, can anyone help me to do this. Thanks

    Read the article

  • Can't add/remove items from a collection while foreach is iterating over it

    - by flockofcode
    If I make my own implementation of IEnumerator interface, then I am able ( inside foreach statement )to add or remove items from a albumsList without generating an exception.But if foreach statement uses IEnumerator supplied by albumsList, then trying to add/delete ( inside the foreach )items from albumsList will result in exception: class Program { static void Main(string[] args) { string[] rockAlbums = { "rock", "roll", "rain dogs" }; ArrayList albumsList = new ArrayList(rockAlbums); AlbumsCollection ac = new AlbumsCollection(albumsList); foreach (string item in ac) { Console.WriteLine(item); albumsList.Remove(item); //works } foreach (string item in albumsList) { albumsList.Remove(item); //exception } } class MyEnumerator : IEnumerator { ArrayList table; int _current = -1; public Object Current { get { return table[_current]; } } public bool MoveNext() { if (_current + 1 < table.Count) { _current++; return true; } else return false; } public void Reset() { _current = -1; } public MyEnumerator(ArrayList albums) { this.table = albums; } } class AlbumsCollection : IEnumerable { public ArrayList albums; public IEnumerator GetEnumerator() { return new MyEnumerator(this.albums); } public AlbumsCollection(ArrayList albums) { this.albums = albums; } } } a) I assume code that throws exception ( when using IEnumerator implementation A supplied by albumsList ) is located inside A? b) If I want to be able to add/remove items from a collection ( while foreach is iterating over it), will I always need to provide my own implementation of IEnumerator interface, or can albumsList be set to allow adding/removing items? thank you

    Read the article

  • Enumerable Interleave Extension Method

    - by João Angelo
    A recent stackoverflow question, which I didn’t bookmark and now I’m unable to find, inspired me to implement an extension method for Enumerable that allows to insert a constant element between each pair of elements in a sequence. Kind of what String.Join does for strings, but maintaining an enumerable as the return value. Having done the single element part I got a bit carried away and ended up expanding it adding overloads to support interleaving elements of another sequence and support for a predicate to control when interleaving takes place. I have to confess that I did this for fun and now I can’t think of any real usage scenario, nonetheless, it may prove useful for someone. First a simple example: var target = new string[] { "(", ")", "(", ")" }; var result = target.Interleave(".", (f, s) => f == "("); // Prints: (.)(.) Console.WriteLine(String.Join(string.Empty, result)); And now the untested but documented implementation: using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class EnumerableExtensions { /// <summary> /// Iterates infinitely over a constant element. /// </summary> /// <typeparam name="T"> /// The type of element in the sequence. /// </typeparam> private class InfiniteSequence<T> : IEnumerable<T>, IEnumerator<T> { public InfiniteSequence(T element) { this.Element = element; } public T Element { get; private set; } public IEnumerator<T> GetEnumerator() { return this; } IEnumerator IEnumerable.GetEnumerator() { return this; } T IEnumerator<T>.Current { get { return this.Element; } } void IDisposable.Dispose() { } object IEnumerator.Current { get { return this.Element; } } bool IEnumerator.MoveNext() { return true; } void IEnumerator.Reset() { } } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence. /// </summary> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="element"> /// The element used to perform the interleave operation. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="element"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, T element) { if (target == null) throw new ArgumentNullException("target"); if (element == null) throw new ArgumentNullException("element"); return InterleaveInternal(target, new InfiniteSequence<T>(element), (f, s) => true); } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence. /// </summary> /// <remarks> /// The interleave operation is interrupted as soon as the <paramref name="target"/> sequence is exhausted; If the number of <paramref name="elements"/> to be interleaved are not enough to completely interleave the <paramref name="target"/> sequence then the remainder of the sequence is returned without being interleaved. /// </remarks> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="elements"> /// The elements used to perform the interleave operation. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="elements"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, IEnumerable<T> elements) { if (target == null) throw new ArgumentNullException("target"); if (elements == null) throw new ArgumentNullException("elements"); return InterleaveInternal(target, elements, (f, s) => true); } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence that satisfy <paramref name="predicate"/>. /// </summary> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="element"> /// The element used to perform the interleave operation. /// </param> /// <param name="predicate"> /// A predicate used to assert if interleaving should occur between two target elements. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> or <paramref name="predicate"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="element"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, T element, Func<T, T, bool> predicate) { if (target == null) throw new ArgumentNullException("target"); if (element == null) throw new ArgumentNullException("element"); if (predicate == null) throw new ArgumentNullException("predicate"); return InterleaveInternal(target, new InfiniteSequence<T>(element), predicate); } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence that satisfy <paramref name="predicate"/>. /// </summary> /// <remarks> /// The interleave operation is interrupted as soon as the <paramref name="target"/> sequence is exhausted; If the number of <paramref name="elements"/> to be interleaved are not enough to completely interleave the <paramref name="target"/> sequence then the remainder of the sequence is returned without being interleaved. /// </remarks> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="elements"> /// The elements used to perform the interleave operation. /// </param> /// <param name="predicate"> /// A predicate used to assert if interleaving should occur between two target elements. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> or <paramref name="predicate"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="elements"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, IEnumerable<T> elements, Func<T, T, bool> predicate) { if (target == null) throw new ArgumentNullException("target"); if (elements == null) throw new ArgumentNullException("elements"); if (predicate == null) throw new ArgumentNullException("predicate"); return InterleaveInternal(target, elements, predicate); } private static IEnumerable<T> InterleaveInternal<T>( this IEnumerable<T> target, IEnumerable<T> elements, Func<T, T, bool> predicate) { var targetEnumerator = target.GetEnumerator(); if (targetEnumerator.MoveNext()) { var elementsEnumerator = elements.GetEnumerator(); while (true) { T first = targetEnumerator.Current; yield return first; if (!targetEnumerator.MoveNext()) yield break; T second = targetEnumerator.Current; bool interleave = true && predicate(first, second) && elementsEnumerator.MoveNext(); if (interleave) yield return elementsEnumerator.Current; } } } }

    Read the article

  • Why enumerator structs are a really bad idea

    - by Simon Cooper
    If you've ever poked around the .NET class libraries in Reflector, I'm sure you would have noticed that the generic collection classes all have implementations of their IEnumerator as a struct rather than a class. As you will see, this design decision has some rather unfortunate side effects... As is generally known in the .NET world, mutable structs are a Very Bad Idea; and there are several other blogs around explaining this (Eric Lippert's blog post explains the problem quite well). In the BCL, the generic collection enumerators are all mutable structs, as they need to keep track of where they are in the collection. This bit me quite hard when I was coding a wrapper around a LinkedList<int>.Enumerator. It boils down to this code: sealed class EnumeratorWrapper : IEnumerator<int> { private readonly LinkedList<int>.Enumerator m_Enumerator; public EnumeratorWrapper(LinkedList<int> linkedList) { m_Enumerator = linkedList.GetEnumerator(); } public int Current { get { return m_Enumerator.Current; } } object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { return m_Enumerator.MoveNext(); } public void Reset() { ((System.Collections.IEnumerator)m_Enumerator).Reset(); } public void Dispose() { m_Enumerator.Dispose(); } } The key line here is the MoveNext method. When I initially coded this, I thought that the call to m_Enumerator.MoveNext() would alter the enumerator state in the m_Enumerator class variable and so the enumeration would proceed in an orderly fashion through the collection. However, when I ran this code it went into an infinite loop - the m_Enumerator.MoveNext() call wasn't actually changing the state in the m_Enumerator variable at all, and my code was looping forever on the first collection element. It was only after disassembling that method that I found out what was going on The MoveNext method above results in the following IL: .method public hidebysig newslot virtual final instance bool MoveNext() cil managed { .maxstack 1 .locals init ( [0] bool CS$1$0000, [1] valuetype [System]System.Collections.Generic.LinkedList`1/Enumerator CS$0$0001) L_0000: nop L_0001: ldarg.0 L_0002: ldfld valuetype [System]System.Collections.Generic.LinkedList`1/Enumerator EnumeratorWrapper::m_Enumerator L_0007: stloc.1 L_0008: ldloca.s CS$0$0001 L_000a: call instance bool [System]System.Collections.Generic.LinkedList`1/Enumerator::MoveNext() L_000f: stloc.0 L_0010: br.s L_0012 L_0012: ldloc.0 L_0013: ret } Here, the important line is 0002 - m_Enumerator is accessed using the ldfld operator, which does the following: Finds the value of a field in the object whose reference is currently on the evaluation stack. So, what the MoveNext method is doing is the following: public bool MoveNext() { LinkedList<int>.Enumerator CS$0$0001 = this.m_Enumerator; bool CS$1$0000 = CS$0$0001.MoveNext(); return CS$1$0000; } The enumerator instance being modified by the call to MoveNext is the one stored in the CS$0$0001 variable on the stack, and not the one in the EnumeratorWrapper class instance. Hence why the state of m_Enumerator wasn't getting updated. Hmm, ok. Well, why is it doing this? If you have a read of Eric Lippert's blog post about this issue, you'll notice he quotes a few sections of the C# spec. In particular, 7.5.4: ...if the field is readonly and the reference occurs outside an instance constructor of the class in which the field is declared, then the result is a value, namely the value of the field I in the object referenced by E. And my m_Enumerator field is readonly! Indeed, if I remove the readonly from the class variable then the problem goes away, and the code works as expected. The IL confirms this: .method public hidebysig newslot virtual final instance bool MoveNext() cil managed { .maxstack 1 .locals init ( [0] bool CS$1$0000) L_0000: nop L_0001: ldarg.0 L_0002: ldflda valuetype [System]System.Collections.Generic.LinkedList`1/Enumerator EnumeratorWrapper::m_Enumerator L_0007: call instance bool [System]System.Collections.Generic.LinkedList`1/Enumerator::MoveNext() L_000c: stloc.0 L_000d: br.s L_000f L_000f: ldloc.0 L_0010: ret } Notice on line 0002, instead of the ldfld we had before, we've got a ldflda, which does this: Finds the address of a field in the object whose reference is currently on the evaluation stack. Instead of loading the value, we're loading the address of the m_Enumerator field. So now the call to MoveNext modifies the enumerator stored in the class rather than on the stack, and everything works as expected. Previously, I had thought enumerator structs were an odd but interesting feature of the BCL that I had used in the past to do linked list slices. However, effects like this only underline how dangerous mutable structs are, and I'm at a loss to explain why the enumerators were implemented as structs in the first place. (interestingly, the SortedList<TKey, TValue> enumerator is a struct but is private, which makes it even more odd - the only way it can be accessed is as a boxed IEnumerator!). I would love to hear people's theories as to why the enumerators are implemented in such a fashion. And bonus points if you can explain why LinkedList<int>.Enumerator.Reset is an explicit implementation but Dispose is implicit... Note to self: never ever ever code a mutable struct.

    Read the article

  • Escaping Generics with T4 Templates

    - by Gavin Stevens
    I've been doing some work with T4 templates lately and ran into an issue which I couldn't find an answer to anywhere.  I finally figured it out, so I thought I'd share the solution. I was trying to generate a code class with a T4 template which used generics The end result a method like: public IEnumerator GetEnumerator()             {                 return new TableEnumerator<Table>(_page);             } the related section of the T4 template looks like this:  public IEnumerator GetEnumerator()             {                 return new TableEnumerator<#=renderClass.Name#>(_page);             } But this of course is missing the Generic Syntax for < > which T4 complains about because < > are reserved. using syntax like <#<#><#=renderClass.Name#><#=<#> won't work becasue the TextTransformation engine chokes on them.  resulting in : Error 2 The number of opening brackets ('<#') does not match the number of closing brackets ('#>')  even trying to escape the characters won't work: <#\<#><#=renderClass.Name#><#\<#> this results in: Error 4 A Statement cannot appear after the first class feature in the template. Only boilerplate, expressions and other class features are allowed after the first class feature block.  The final solution delcares a few strings to represent the literals like this: <#+    void RenderCollectionEnumerator(RenderCollection renderClass)  {     string open = "<";   string close =">"; #>    public partial class <#=renderClass.Name#> : IEnumerable         {             private readonly PageBase _page;             public <#=renderClass.Name#>(PageBase page)             {                 _page = page;             }             public IEnumerator GetEnumerator()             {                 return new TableEnumerator<#=open#><#=renderClass.Name#><#=close#>(_page);             }         } <#+  }  #> This works, and everyone is happy, resulting in an automatically generated class enumerator, complete with generics! Hopefully this will save someone some time :)

    Read the article

  • Understanding C# async / await (2) Awaitable / Awaiter Pattern

    - by Dixin
    What is awaitable Part 1 shows that any Task is awaitable. Actually there are other awaitable types. Here is an example: Task<int> task = new Task<int>(() => 0); int result = await task.ConfigureAwait(false); // Returns a ConfiguredTaskAwaitable<TResult>. The returned ConfiguredTaskAwaitable<TResult> struct is awaitable. And it is not Task at all: public struct ConfiguredTaskAwaitable<TResult> { private readonly ConfiguredTaskAwaiter m_configuredTaskAwaiter; internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext) { this.m_configuredTaskAwaiter = new ConfiguredTaskAwaiter(task, continueOnCapturedContext); } public ConfiguredTaskAwaiter GetAwaiter() { return this.m_configuredTaskAwaiter; } } It has one GetAwaiter() method. Actually in part 1 we have seen that Task has GetAwaiter() method too: public class Task { public TaskAwaiter GetAwaiter() { return new TaskAwaiter(this); } } public class Task<TResult> : Task { public new TaskAwaiter<TResult> GetAwaiter() { return new TaskAwaiter<TResult>(this); } } Task.Yield() is a another example: await Task.Yield(); // Returns a YieldAwaitable. The returned YieldAwaitable is not Task either: public struct YieldAwaitable { public YieldAwaiter GetAwaiter() { return default(YieldAwaiter); } } Again, it just has one GetAwaiter() method. In this article, we will look at what is awaitable. The awaitable / awaiter pattern By observing different awaitable / awaiter types, we can tell that an object is awaitable if It has a GetAwaiter() method (instance method or extension method); Its GetAwaiter() method returns an awaiter. An object is an awaiter if: It implements INotifyCompletion or ICriticalNotifyCompletion interface; It has an IsCompleted, which has a getter and returns a Boolean; it has a GetResult() method, which returns void, or a result. This awaitable / awaiter pattern is very similar to the iteratable / iterator pattern. Here is the interface definitions of iteratable / iterator: public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); } public interface IEnumerable<out T> : IEnumerable { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<out T> : IDisposable, IEnumerator { T Current { get; } } In case you are not familiar with the out keyword, please find out the explanation in Understanding C# Covariance And Contravariance (2) Interfaces. The “missing” IAwaitable / IAwaiter interfaces Similar to IEnumerable and IEnumerator interfaces, awaitable / awaiter can be visualized by IAwaitable / IAwaiter interfaces too. This is the non-generic version: public interface IAwaitable { IAwaiter GetAwaiter(); } public interface IAwaiter : INotifyCompletion // or ICriticalNotifyCompletion { // INotifyCompletion has one method: void OnCompleted(Action continuation); // ICriticalNotifyCompletion implements INotifyCompletion, // also has this method: void UnsafeOnCompleted(Action continuation); bool IsCompleted { get; } void GetResult(); } Please notice GetResult() returns void here. Task.GetAwaiter() / TaskAwaiter.GetResult() is of such case. And this is the generic version: public interface IAwaitable<out TResult> { IAwaiter<TResult> GetAwaiter(); } public interface IAwaiter<out TResult> : INotifyCompletion // or ICriticalNotifyCompletion { bool IsCompleted { get; } TResult GetResult(); } Here the only difference is, GetResult() return a result. Task<TResult>.GetAwaiter() / TaskAwaiter<TResult>.GetResult() is of this case. Please notice .NET does not define these IAwaitable / IAwaiter interfaces at all. As an UI designer, I guess the reason is, IAwaitable interface will constraint GetAwaiter() to be instance method. Actually C# supports both GetAwaiter() instance method and GetAwaiter() extension method. Here I use these interfaces only for better visualizing what is awaitable / awaiter. Now, if looking at above ConfiguredTaskAwaitable / ConfiguredTaskAwaiter, YieldAwaitable / YieldAwaiter, Task / TaskAwaiter pairs again, they all “implicitly” implement these “missing” IAwaitable / IAwaiter interfaces. In the next part, we will see how to implement awaitable / awaiter. Await any function / action In C# await cannot be used with lambda. This code: int result = await (() => 0); will cause a compiler error: Cannot await 'lambda expression' This is easy to understand because this lambda expression (() => 0) may be a function or a expression tree. Obviously we mean function here, and we can tell compiler in this way: int result = await new Func<int>(() => 0); It causes an different error: Cannot await 'System.Func<int>' OK, now the compiler is complaining the type instead of syntax. With the understanding of the awaitable / awaiter pattern, Func<TResult> type can be easily made into awaitable. GetAwaiter() instance method, using IAwaitable / IAwaiter interfaces First, similar to above ConfiguredTaskAwaitable<TResult>, a FuncAwaitable<TResult> can be implemented to wrap Func<TResult>: internal struct FuncAwaitable<TResult> : IAwaitable<TResult> { private readonly Func<TResult> function; public FuncAwaitable(Func<TResult> function) { this.function = function; } public IAwaiter<TResult> GetAwaiter() { return new FuncAwaiter<TResult>(this.function); } } FuncAwaitable<TResult> wrapper is used to implement IAwaitable<TResult>, so it has one instance method, GetAwaiter(), which returns a IAwaiter<TResult>, which wraps that Func<TResult> too. FuncAwaiter<TResult> is used to implement IAwaiter<TResult>: public struct FuncAwaiter<TResult> : IAwaiter<TResult> { private readonly Task<TResult> task; public FuncAwaiter(Func<TResult> function) { this.task = new Task<TResult>(function); this.task.Start(); } bool IAwaiter<TResult>.IsCompleted { get { return this.task.IsCompleted; } } TResult IAwaiter<TResult>.GetResult() { return this.task.Result; } void INotifyCompletion.OnCompleted(Action continuation) { new Task(continuation).Start(); } } Now a function can be awaited in this way: int result = await new FuncAwaitable<int>(() => 0); GetAwaiter() extension method As IAwaitable shows, all that an awaitable needs is just a GetAwaiter() method. In above code, FuncAwaitable<TResult> is created as a wrapper of Func<TResult> and implements IAwaitable<TResult>, so that there is a  GetAwaiter() instance method. If a GetAwaiter() extension method  can be defined for Func<TResult>, then FuncAwaitable<TResult> is no longer needed: public static class FuncExtensions { public static IAwaiter<TResult> GetAwaiter<TResult>(this Func<TResult> function) { return new FuncAwaiter<TResult>(function); } } So a Func<TResult> function can be directly awaited: int result = await new Func<int>(() => 0); Using the existing awaitable / awaiter - Task / TaskAwaiter Remember the most frequently used awaitable / awaiter - Task / TaskAwaiter. With Task / TaskAwaiter, FuncAwaitable / FuncAwaiter are no longer needed: public static class FuncExtensions { public static TaskAwaiter<TResult> GetAwaiter<TResult>(this Func<TResult> function) { Task<TResult> task = new Task<TResult>(function); task.Start(); return task.GetAwaiter(); // Returns a TaskAwaiter<TResult>. } } Similarly, with this extension method: public static class ActionExtensions { public static TaskAwaiter GetAwaiter(this Action action) { Task task = new Task(action); task.Start(); return task.GetAwaiter(); // Returns a TaskAwaiter. } } an action can be awaited as well: await new Action(() => { }); Now any function / action can be awaited: await new Action(() => HelperMethods.IO()); // or: await new Action(HelperMethods.IO); If function / action has parameter(s), closure can be used: int arg0 = 0; int arg1 = 1; int result = await new Action(() => HelperMethods.IO(arg0, arg1)); Using Task.Run() The above code is used to demonstrate how awaitable / awaiter can be implemented. Because it is a common scenario to await a function / action, so .NET provides a built-in API: Task.Run(): public class Task2 { public static Task Run(Action action) { // The implementation is similar to: Task task = new Task(action); task.Start(); return task; } public static Task<TResult> Run<TResult>(Func<TResult> function) { // The implementation is similar to: Task<TResult> task = new Task<TResult>(function); task.Start(); return task; } } In reality, this is how we await a function: int result = await Task.Run(() => HelperMethods.IO(arg0, arg1)); and await a action: await Task.Run(() => HelperMethods.IO());

    Read the article

  • Synchronized Enumerator in C#

    - by Dan Bryant
    I'm putting together a custom SynchronizedCollection<T> class so that I can have a synchronized Observable collection for my WPF application. The synchronization is provided via a ReaderWriterLockSlim, which, for the most part, has been easy to apply. The case I'm having trouble with is how to provide thread-safe enumeration of the collection. I've created a custom IEnumerator<T> nested class that looks like this: private class SynchronizedEnumerator : IEnumerator<T> { private SynchronizedCollection<T> _collection; private int _currentIndex; internal SynchronizedEnumerator(SynchronizedCollection<T> collection) { _collection = collection; _collection._lock.EnterReadLock(); _currentIndex = -1; } #region IEnumerator<T> Members public T Current { get; private set;} #endregion #region IDisposable Members public void Dispose() { var collection = _collection; if (collection != null) collection._lock.ExitReadLock(); _collection = null; } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { var collection = _collection; if (collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex++; if (_currentIndex >= collection.Count) { Current = default(T); return false; } Current = collection[_currentIndex]; return true; } public void Reset() { if (_collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex = -1; Current = default(T); } #endregion } My concern, however, is that if the Enumerator is not Disposed, the lock will never be released. In most use cases, this is not a problem, as foreach should properly call Dispose. It could be a problem, however, if a consumer retrieves an explicit Enumerator instance. Is my only option to document the class with a caveat implementer reminding the consumer to call Dispose if using the Enumerator explicitly or is there a way to safely release the lock during finalization? I'm thinking not, since the finalizer doesn't even run on the same thread, but I was curious if there other ways to improve this.

    Read the article

  • Does .NET have a built in IEnumerable for multiple collections?

    - by Bryce Wagner
    I need an easy way to iterate over multiple collections without actually merging them, and I couldn't find anything built into .NET that looks like it does that. It feels like this should be a somewhat common situation. I don't want to reinvent the wheel. Is there anything built in that does something like this: public class MultiCollectionEnumerable<T> : IEnumerable<T> { private MultiCollectionEnumerator<T> enumerator; public MultiCollectionEnumerable(params IEnumerable<T>[] collections) { enumerator = new MultiCollectionEnumerator<T>(collections); } public IEnumerator<T> GetEnumerator() { enumerator.Reset(); return enumerator; } IEnumerator IEnumerable.GetEnumerator() { enumerator.Reset(); return enumerator; } private class MultiCollectionEnumerator<T> : IEnumerator<T> { private IEnumerable<T>[] collections; private int currentIndex; private IEnumerator<T> currentEnumerator; public MultiCollectionEnumerator(IEnumerable<T>[] collections) { this.collections = collections; this.currentIndex = -1; } public T Current { get { if (currentEnumerator != null) return currentEnumerator.Current; else return default(T); } } public void Dispose() { if (currentEnumerator != null) currentEnumerator.Dispose(); } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { if (currentIndex >= collections.Length) return false; if (currentIndex < 0) { currentIndex = 0; if (collections.Length > 0) currentEnumerator = collections[0].GetEnumerator(); else return false; } while (!currentEnumerator.MoveNext()) { currentEnumerator.Dispose(); currentEnumerator = null; currentIndex++; if (currentIndex >= collections.Length) return false; currentEnumerator = collections[currentIndex].GetEnumerator(); } return true; } public void Reset() { if (currentEnumerator != null) { currentEnumerator.Dispose(); currentEnumerator = null; } this.currentIndex = -1; } } }

    Read the article

  • Error message regarding IEnumerable.GetEnumerator().

    - by Bon_chan
    I get this error message and I can't figure out why! Error 1 'Exo5Chap12.ShortCollection<T>' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'Exo5Chap12.ShortCollection<T>.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'. E:\MyFolders\Dev\c#\Chapter12\Exo5Chap12\Exo5Chap12\exo5.cs 9 18 Exo5Chap12 Here is the code with an implementation of GetEnumerator(). What is wrong? public class ShortCollection<T> : IList<T> { protected Collection<T> innerCollection; protected int maxSize = 10; public IEnumerator<T> GetEnumerator() { return (innerCollection as IEnumerator<T>).GetEnumerator(); } }

    Read the article

1 2 3 4 5  | Next Page >