John
John

Reputation: 115

Object creation from list <Class>

I want to create a new instance of a object which is holding a list object of another class.

public Class A
{
    int a { get; set; };

    List<B> b  { get; set; }

}




public Class B
{
    int c { get; set; };
}



public Class Test
{
    A a= new A();
    a.b= ? how to initiate this

    a.b.c=some value;

}

I am not getting this value c here.how to get This value.

Upvotes: 0

Views: 46

Answers (2)

Peter Punzenberger
Peter Punzenberger

Reputation: 561

Try it this way:

public Class A
{
    public int a { get; set; };

    public List<B> b  { get; set; }

    public A()
    {
        b = new List<B>();
    }
}




public Class B
{
    public int c { get; set; };
}  



public Class Test
{
    A a= new A();
    a.b= ? how to initiate this

    a.b.Add(new B(){c = 13};
}

Upvotes: 1

Gopinath
Gopinath

Reputation: 27

1.Try this initializing method

       A objA = new A();

        objA.a = 10;

        objA.b = new List<B> { new B { C = 20 }, new B { C = 40 }, new B { C = 50 }, new B { C = 60 } };

2.Or try this one

     A objA = new A();

        objA.a = 10;           

        List<B> bList = new List<B>();

        bList.Add(new B { C = 20 });
        bList.Add(new B { C = 40 });
        bList.Add(new B { C = 50 });
        bList.Add(new B {C=60});

        objA.b = bList;

And modify access specifiers of properties.

Upvotes: 0

Related Questions