Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 549
BrainCoder Avatar asked Feb 24 '26 02:02

BrainCoder


2 Answers

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; 
 }
like image 51
Jens Kloster Avatar answered Feb 25 '26 15:02

Jens Kloster


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>.

like image 20
Hossein Narimani Rad Avatar answered Feb 25 '26 15:02

Hossein Narimani Rad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!