Home > Net >  Add items to List<object>
Add items to List<object>

Time:04-12

I am new to OOPS. I want to add items to a list of objects

Class ABC
{ int a, int b, int c}

List<ABC> listabc = new List<ABC>();

I want to add items to this list with different calls, for example:

listabc.Add(new ABC {a = 10});
listabc.Add(new ABC {b = 20});
listabc.Add(new ABC {c = 30});

this will add ((10,0,0),(0,20,0),(0,0,30)) to the list. I want it to be (10,20,30), how should I add it to the list?

CodePudding user response:

You need to add them all at once.

listabc.Add(new ABC {a = 10, b=20, c=30});

In your example, you are creating a new class each time and populating a different property. You are getting zeros when you do not provide value because the default value for int is 0;

CodePudding user response:

One thing you could do is set up a constructor on your class to pass through the variables:

public class ABC
{
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }

    public ABC (int a, int b, int c) {
        A = a;
        B = b;
        C = c;
    }
}

Then when you populate your class, you can specify the values in your constructor:

List<ABC> listabc = new List<ABC>();
listabc.Add(new ABC(10,20,30));

Otherwise, when you add an object you need to ensure you specify all parameters.

The way you were adding them, it was the equivalent of only passing through one value, e.g.

listabc.Add(new ABC(10,0,0));
listabc.Add(new ABC(0,20,0));
listabc.Add(new ABC(0,0,30));

CodePudding user response:

Only

listabc.Add(new ABC {10, 20, 30});

Console.Write ($"{listabc[0].a}, {listabc[0].b}, {listabc[0].c}");

it's all

  •  Tags:  
  • c#
  • Related