简体   繁体   中英

getting list.Count zero after adding element using .Add() method in property

Below is my code

private List<string> _myList
public List<string> myList
{
     get
     {
         if (Session["MyData"] != null)
            _myList = Session["MyData"] as List<string>;
         if(_myList==null)
            _myList = new List<string>();
         return _myList; 
      }

     set 
     { 
         Session["MyData"] = value; 
     }
  }

Now when I call

 myList.add(new string("string1"));

and use

 myList.Count 

I am getting myList.Count equals 0 I don't know what is the problem with my code.

this overrides the list:

 get
 {
     if (Session["MyData"] != null)
        _myList = Session["MyData"] as List<string>; //<-- here
     if(_myList==null)
        _myList = new List<string>();
     return _myList; 
 }

Try changing it to:

 get
 {
     if(_myList != null)
       return _mylist;

     if (Session["MyData"] != null)
        _myList = Session["MyData"] as List<string>;
     else
        _myList = new List<string>();

     return _myList; 
 }

You are not modifying the _myList . In your get , sometimes you return a new List<string> so you Add the new item to that new List and when calling it again you count the member for another new List<string> .

get
{
   if(_myList != null)
   { 
      Session["MyData"] = _myList;   // change
      return _myList;
   }

   if (Session["MyData"] != null)
      _myList = Session["MyData"] as List<string>;
   else
      _myList = new List<string>();

   return _myList; 
}
set
{
    _myList = value;         //change
    Session["MyData"] = value;
}

The property getter doesn't set Session["MyData"] = new List<string>(); correctly.

Change your code to:

public List<string> myList
{
     get
     {
         return Session["MyData"] ?? (Session["MyData"] == new List<string>());
     }

     set 
     { 
         Session["MyData"] = value; 
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM