Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign reference to list properly c#

I'm trying to add strings to a List<string> so I can print them with a loop in a certain point of time, being more specific here is part of my code:

public class Foo{
    public string propertyA;
    public string propertyB;
    public string propertyC;
    public List<string> list;
    Public Foo(){
         list = new List<string>();
         list.Add(propertyA);
         list.Add(propertyB);
         list.Add(propertyC);
    }
}

In later code, after assigning propertyA and the other variables and trying to iterate over the List I get empty strings. I require the properties to be in the list. My questions is which would be the best way to achieve this?

like image 627
user1998791 Avatar asked Feb 15 '26 01:02

user1998791


1 Answers

Looks like you are getting empty strings because when you are adding to the list the values in your properties have not been set at the time that the Foo() constructor is called...

Try passing values and setting them in the Foo constructor as follows:

public class Foo{
    public string propertyA;
    public string propertyB;
    public string propertyC;
    public List<string> list;
    Public Foo(string propA, string propB, string propC){
         propertyA = propA;
         propertyB = propB;
         propertyC = propC;
         list = new List<string>();
         list.Add(propertyA);
         list.Add(propertyB);
         list.Add(propertyC);
    }
}

Alternatively you could add the values to the list at a later time when the properties are actually set and not in the constructor e.g.

public string PropertyA
{
    //set the person name
    set {  propertyA = value;
           list.Add(value); 
        }
    //get the person name 
    get { return propertyA; }
}
...
like image 179
Louie Bacaj Avatar answered Feb 16 '26 14:02

Louie Bacaj



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!