Michal_LFC
Michal_LFC

Reputation: 599

c# list.Add complication

I have class MyClass() in which I am calling method from another SecondClass() it is done is foreach loop. In this method I have a list to which I am putting some data. But everytime this method is called my list is filled from the begining. I lose all previously inserted data. How can I fix this problem?

foreach(string items in description)
{
    SecondClass method = new SecondClass();
    method.DoThis(items);
}

MyClass() with this method looks something like this

public void DoThis(string items)
{
    List<MyClass> list2 = new List<MyClass>();
    if(//somethis)
    {
         /// some more code
         list2.Add(sk);
    }
}

I edited the code, I had some mistakes. Sorry

Upvotes: 0

Views: 109

Answers (2)

KappaG3
KappaG3

Reputation: 671

You're initializing list2 inside DoThis's scope. You have to declare it as a member of MyClass, like the following:

class MyClass
{
      //if MyClass is sealed or static, then change protected to private.
      //if you need to access it from outside MyClass, change it to public.
      protected List<SrodkowaKolumna> list2 = new List<SrodkowaKolumna>();

      public void DoThis(string items)
      {
           if(//somethis)
           {
                 /// some more code
                 list2.Add(sk);
           }
      }
 }

Upvotes: 2

Kamil Budziewski
Kamil Budziewski

Reputation: 23107

Try this code:

It should store your list as field in class. When you were initializing list2 in DoThis, every single call was making new empty list2.

public class MyClass
{
    List<SrodkowaKolumna> list2;
    public MyClass()
    {
         list2 = new List<SrodkowaKolumna>();
    }
    //.... other code

    public void DoThis(string items)
    {  
       for(//somethis)
       {
         /// some more code
                list2.Add(sk);
       }
     }
}

Upvotes: 0

Related Questions