sly_Chandan
sly_Chandan

Reputation: 3515

Why cant I create a generic list of my class type?

public partial class About : System.Web.UI.Page
{
    public class Class2
    {
        public int i = 1;
        public string str = "Chandan";

    }


    protected void Page_Load(object sender, EventArgs e)
    {

        List<Class2> Object2 = new List<Class2>();

    }

}

Upvotes: 0

Views: 211

Answers (4)

sly_Chandan
sly_Chandan

Reputation: 3515

Output of the following code List count = 1

public partial class About : System.Web.UI.Page
{
    public class Class2
    {
        public int i = 1;
        public string str = "Chandan";
        public string Data()
        {
            return i.ToString() + " " + str.ToString();
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {

        Class2 Object1 = new Class2();
        List<Class2> Object2 = new List<Class2>();
        Object2.Add(Object1);
        Response.Write("List count = " + Object2.Count.ToString());    
    }

}

You are right Matt. Thanks for the explanation. You Rock!!!

Upvotes: 0

CodesInChaos
CodesInChaos

Reputation: 108800

List<Class2> Object2 = new List<Class2>();
Object2.Add(new Class2());
Console.WriteLine(Object2[0].str);

I see no reason why Object2[0] shouldn't have accessible fields. And I just tested in LinqPad, and it worked correctly.

Or alternatively without a List:

Class2 Object2 = new Class2();
Console.WriteLine(Object2.str);

It's usually bad style to use public fields, but apart from that your code is ok and works.

Upvotes: 1

Oded
Oded

Reputation: 499002

You are creating a collection of your objects.

In order to access the public fields of each object, you need to access each object in the list.

Did you mean?

Class2 Object2 = new Class2();

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101604

List<Class2> Object2 = new List<Class2>(new[]{ new Class2(); });
Console.Out("{0}. {1}", Object2[0].i, Object2[0].str);

Should work fine.

Upvotes: 0

Related Questions