0

I have a list i am trying to pass from one class to another. Here is the code:

namespace Test
{
    Class1
    {
            public IList<string> MyList { get; set; }
            internal Class1()
            {
                            MyList = new List<string>();
            }
            public void AddValues()
            {
                            MyList.Add("123");
            }             
    }
}


Class2
{             
        Class1 c = new Class1();
        var a = c.MyList;
}

Everytime i run this i am getting 0 value in Class2 for MYList. What am i doing wrong?

My thinking is it is going to constructor again and initializing MyList again when it is called from Class2. But i cannot initialize MyList in method AddValues either as it is being called many times from another class. So i am confused how can i do this. Searched on google but did not find any answers.

tnw
  • 13,521
  • 15
  • 70
  • 111
NoviceMe
  • 3,126
  • 11
  • 57
  • 117

3 Answers3

3

You just did:

Class1 c = new Class1();
var a = c.MyList;

and you didn't call AddValues method, so your list remained empty.

Try:

Class1 c = new Class1();
c.AddValues(); // call method to add in list
var a = c.MyList;

You shouldn't be exposing List<T> as property, you may see this thread as well.

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
  • AddValues() has lot of other code I do not want to call it again from Class2. All I am trying to do is store a list in Class1 which can just be passed to Class2 – NoviceMe Feb 28 '14 at 15:35
  • @NoviceMe, you haven't added anything in your List, how do you expect it to contain any element just after the constructor call ?? An empty list would remain empty if you don't add anything to it. – Habib Feb 28 '14 at 15:36
  • There is another class let's say Class3 which is calling AddValues method and adding those values. Now in Class2 I am trying to access those values. Hope it makes sense? – NoviceMe Feb 28 '14 at 15:40
0

you need to call AddValues() before you call Mylist because you do not initialize the list when the object is created

Trax5
  • 3
  • 2
0

Based on your commend on Habib's answer, you are describing another problem. If you don't want to call that AddValues-Method again, you are having an architectural problem. Maybe consider reversing the order. Instead of calling

Class2
{             
    Class1 c = new Class1();
    var a = c.MyList;
}

you might want to inject a specific instance of Class1 into your instance of Class2:

public class Class2
{
    private Class1 _dependency;       

    public Class2(Class1 dependency)
    {
         _dependency = dependency;
    }

    public void Whatever()
    {
         _dependency.MyList;
    }
}
ElGauchooo
  • 4,256
  • 2
  • 13
  • 16