user1125105
user1125105

Reputation: 3

Initializing a List

I have created a class student with three properties like this

public class Student
{
    public int age;
    public string name;
    public string course;

    public Student(int age , string name , string course)
    {
        this.age = age;
        this.course = course;
        this.name = name;
    }

    List<Student> school = new List<Student>(
        new Student(12,"ram","ece"));                        
        );
}

what I am trying to do is, I am adding student details manually to student class

but I am getting this error at this line

  new Student(12,"ram","ece"));                        

Error : cannot convert from windowsapplication.student to systems.Collections.Generic.IEnumerable<windowsapplication.Student>

Why is this happening?

Upvotes: 0

Views: 123

Answers (4)

Odys
Odys

Reputation: 9100

Try this:

List<Student> school = new List<Student>();
school.add(new Student(12,"ram","ece"));

Upvotes: 0

Oded
Oded

Reputation: 499352

The syntax you have used is trying to pass a new Student to the constructor of List<Student> - there is no such constructor, hence the error.

You have a small syntax error. This should work:

List<Student> school = new List<Student>{
                        new Student(12,"ram","ece"));                        
                       };

The syntax for collection initializer is with {} not ().

Upvotes: 2

Yahia
Yahia

Reputation: 70379

try

List<Student> school = new List<Student>() { new Student(12,"ram","ece") };

Upvotes: 1

max
max

Reputation: 34447

List<Student> constructor is expecting IEnumerable<Student>, not a single student. I think you actually wanted to use list initializer syntax:

List<Student> school = new List<Student>()
{
    new Student(12,"ram","ece"),
};

Upvotes: 1

Related Questions