6
Reply

Generic Method - Iterate through a generic type

Mark Maguire

Mark Maguire

Jun 8 2011 5:48 AM
2.7k
I have a generic method which I pass an object of a certain type.  This object incorporates IEnumerable and IEnumerator in order to allow iteration using foreach, however when I try to iterate it which in the generic method i gives me this error >> "foreach statement cannot operate on variables of type 'T' because 'T' does not contain a public definition for 'GetEnumerator''

Here is my code:

        private bool GenericSummaryResultComparison<T>(string szRiskRecordFilePath, string szResultSetSchemaFilePath) where T : class
        {
            try
            {
                T oRiskRecord;

                //Read in the result files.
                oRiskRecord = SerializationMethods.DeserializeIt<T>(szResultFilePath1, szResultSetSchemaFilePath);

                foreach (T o in oRiskRecord)
                {
                    // actions
                }

                return true;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message, ex.InnerException);
            }
        }


How can I get this iteration to work?

Thanks


Answers (6)