ICollection Issue

May 30 2011 7:01 AM
I have a class that have two properties

public class FormField 

 public string FormCode { getset; } 
 public string FieldCode { getset; } 
}

I have an another class that implements ICollection<FormField>

public
 class FormFieldCollection : ICollection<FormField

 ICollection<FormField> m_form_field;  


 
 public FormFieldCollection() 
 { 
 m_form_field = new Collection<FormField>(); 
 }
 
 public void Add(FormField item) 
 { 
 m_form_field.Add(item); 
 }  
 public void Clear() 
 { 
 m_form_field.Clear(); 
 }




 public bool Contains(FormField item) 
 { 
 return m_form_field.Contains(item); 
 }
 
 public void CopyTo(FormField[] array, int arrayIndex) 
 { 
 m_form_field.CopyTo(array, arrayIndex); 
 }
 
 public int Count 
 { 
 get { return m_form_field.Count; } 
 }
 
 public bool IsReadOnly 
 { 
 get { return m_form_field.IsReadOnly; } 
 }
 
 public bool Remove(FormField item) 
 { 
 return m_form_field.Remove(item); 
 }
 
 public IEnumerator<FormField> GetEnumerator() 
 { 
 return m_form_field.GetEnumerator(); 
 }

 
IEnumerator
 IEnumerable.GetEnumerator() 
 { 
 return m_form_field.GetEnumerator(); 
 } 
}

I have a method in an another class that is returning ICollection<T> interface

public class FormFieldXmlTesting 

 string filePath = @"C:\RnD\CollectionRnD\FormFieldXml.xml";  


 public ICollection<T> RetriveAllUsingGenerics<T>() where T : class 
 { 
 ICollection<FormField> projectCollection;  
 XDocument document = XDocument.Load(filePath);  


 projectCollection = (from XElement element in document.Elements("FormFields")
 .Elements("Module").Elements("Field")
 select new FormField{
 FormCode = element.Parent.Attribute("Name").Value,
 FieldCode = element.Attribute("Name").Value,
 }).ToList();
 return projectCollection as ICollection<T>; 
 } 
}



When I am calling the above method the output is astonizing me

 FormFieldXmlTesting testing = new FormFieldXmlTesting();  
 
 //Returns correct output 
 ICollection<FormField> coll = testing.RetriveAllUsingGenerics<FormField>();  



 //Returns null values 
 FormFieldCollection collection = testing.RetriveAllUsingGenerics<FormField>() as FormFieldCollection;  
 
Console.WriteLine(string.Format("ICollection<FormField> record fetched: {0}", coll == null ? 0 : coll.Count)); 
Console.WriteLine(string.Format("FormFieldCollection record fetched: {0}", collection == null ? 0 : collection.Count)); 
Console.ReadLine();
 
The xml used in the application is as follows

<FormFields>
 <Module Name="ProjectType">
  <Field Name="ProjectTypeCode">
  </Field>
  <Field Name="ProjectTypeName">
  </Field>
  <Field Name="ProjectTypeDescription">
  </Field>
 </Module>
 <Module Name="ResourceType">
  <Field Name="ResourceTypeCode">
  </Field>
  <Field Name="ResourceTypeName">
  </Field>
  <Field Name="ResourceTypeDescription">
  </Field>
 </Module>
</FormFields>

Answers (1)