Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add the objects of a class in a static List property of same class?

I have a class A and it has 2 normal properties (string properties) and 1 static property (List of type of A). While creating a new instance of Class A, in constructor, I want to add that instance in static list property. I have two questions.

1- Is it possible?

2- If its possible then how can I implement.

I am using following code :

public class A {
private string _property1;
private string _property2;
private static List<A> _AList;

public string Property1 {
  get { return _property1; }
  set { _property1 = value; }
}

public string Property2 {
  get { return _property2; }
  set { _property2 = value; }
}

public static List<A> AList {
  get { return _AList; }
  set { _AList = value; }
}
public A( ) {
}

}

like image 390
User1551892 Avatar asked Dec 06 '22 11:12

User1551892


1 Answers

1 - Is it possible?

Yes.

2 - If its possible then how can I implement.

Initialize the list in a static constructor

static A() {
    AList = new List<A>();
}

Then add the instance in the instance constructor

public A( ) {
    A.AList.Add(this);
}
like image 52
D Stanley Avatar answered Dec 10 '22 02:12

D Stanley