Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new object to List is not working

Tags:

c#

I'm trying to add a new OldFlatFile to OldFlatFileList which works but not on adding new one. I can not see error and I don't know if there's something wrong with the code below?

OldFlatFileList count is same as before and after adding:

    var selectedPackage = FlatFileHelper.GetSelectedPackage(OldFlatFileList);
    var primaryFeature = new PrimaryFeatures(){ DataTypeCode = "abc" };

    OldFlatFileList.ToList().Add(
    new OldFlatFile
    {
        new OldFlatFileEntry
        {
            InformationFields = selectedPackage.InformationFields,
            PrimaryFeatures = primaryFeature,
            SecondaryFeatures = null
        }
    });

    private IEnumerable<OldFlatFile> OldFlatFileList
    {
        get { return Session[SystemConstant.OldFlatFileListKey] as List<OldFlatFile>; }
        set { Session[SystemConstant.OldFlatFileListKey] = value; }
    }

    public class OldFlatFile : List<OldFlatFileEntry>
    {}
like image 476
htcdmrl Avatar asked Dec 31 '13 14:12

htcdmrl


1 Answers

OldFlatFileList.ToList() creates new instance of list (which will have copies of items from original list). Then you are adding new object to that new list, but you don't save reference to new list in any variable. So your new list with added item simply will be collected by garbage collector. Original list will stay unchanged (because you didn't add item to it).

Thus you can't add items to variable of IEnumerable<T> type (it supports only enumeration), I suggest you to change OldFlatFileList property type to List<OldFlatFile>, or IList<OldFlatFile> or ICollection<OldFlatFile>. Then simply call:

 OldFlatFileList.Add(new OldFlatFile { ... });

That will modify your original list.

like image 179
Sergey Berezovskiy Avatar answered Nov 03 '22 22:11

Sergey Berezovskiy