System.Windows.Forms.ListBindingHelper.GetFirstItemByEnumerable C# (CSharp) Method

GetFirstItemByEnumerable() private static method

private static GetFirstItemByEnumerable ( IEnumerable enumerable ) : object
enumerable IEnumerable
return object
        private static object GetFirstItemByEnumerable(IEnumerable enumerable) {
            object instance = null;

            if (enumerable is IList) {
                // If the list supports IList (which is a superset of IEnumerable), then try to use its IList indexer
                // to get the first item, since some ILists don't support use of their plain IEnumerable interface.
                IList list = enumerable as IList;
                instance = (list.Count > 0) ? list[0] : null;
            }
            else {
                // Otherwise use the enumerator to get the first item...
                try {
                    IEnumerator listEnumerator = enumerable.GetEnumerator();

                    listEnumerator.Reset();

                    if (listEnumerator.MoveNext())
                        instance = listEnumerator.Current;

                    // after we are done w/ the enumerator, reset it
                    listEnumerator.Reset();
                }
                catch (NotSupportedException) {
                    // Some data sources do not offer a full implementation of IEnumerable. For example, SqlDataReader
                    // only supports reading forwards through items, so it does not support calls to IEnumerable.Reset().
                    instance = null;
                }
            }

            return instance;
        }