How do you sort a C# array in descending or reverse order? A simple way is to sort the array in ascending order, then reverse it:
This article provides C# code for an empty enumerator. This generic class can be used to simulate enumeration over an empty collection of any type of objects. Here is the code:
It’s possible to provide multiple generic enumerators for a single class. The trick is that clients must specify which enumerator to use.
It’s important to note that an enumerator does not have exclusive, thread-safe access to its collection. Even when a collection is synchronized, other threads can still modify the collection. Therefore, a collection’s contents can change while enumerating through it, which will cause the enumerator to throw an exception. So there are three key ways to safely enumerate a collection:
Multi-threaded code is challenging to get right and even harder to debug once it’s gone wrong. This is especially true when attempting to collect data from multiple threads. To make this easier, many .NET collection classes include the SyncRoot property to maintain proper synchronization with other threads that might be simultaneously modifying the collection. But then Microsoft changed its mind in .NET 2.0 and decided to let the developer decide how to manage synchronization, and so none of the new generic collections have a SyncRoot property.
It’s easy to reverse the contents of an array using C# generics:
As discussed in a previous article, Generics provides the ability to create strongly-typed collections in C#. Unfortunately, C# currently does not support generics variance, which would allow inheritance of generic types.
If you need a collection of objects accessed by a key, and the key is one of the object’s properties, then you should use the KeyedCollection class instead of Dictionary. For example, you would use a KeyedCollection to store Employee objects accessed by the employee’s ID property.
Generics in .NET 2.0 provides the ability to create strongly-typed collections in C#. Unfortunately, C# currently does not support generics variance, which would allow inheritance of generic types.
For example, consider a list of strings and a list of objects:
List<string> strings = new List<string>(); strings.Add( "hello" ); strings.Add( "goodbye" ); List<object> objects = new List<object>(); objects.AddRange( strings );
The final line in the code above generates a compiler error. But why? Since the ’string’ class derives from the ‘object’ class, one would expect List<string> to also implicitly derive from List<object>. This capability is called generics variance, but C# currently does not support it.
Fortunately, you can brute force your way to a solution by creating a generic ConvertIEnumerable method:
