Saniya
Saniya

Reputation: 35

Returning a list of elements with method

I need to create a method that will return 3-4 courses. The objects are initialized with data and a list of 3-4 courses is returned.

How can this be done? I created a method of class type. How can I add these objects to list and return them?

What I do is:

List<DummyCourse> GetDummyCoursesList()
{
     var Course1 = new DummyCourse()
     {
        CourseId = 1,
        Name = "DataStructures",
        CourseLength = 4,
        CourseType = 1,
        CreatedAt = DateTime.Now,
        CreatedBy = "Teacher",
        ModifiedAt = DateTime.Now,
        ModifiedBy = "Teacher"
     };
     var Course2 = new DummyCourse()
     {
        CourseId = 2,
        Name = "Mathematics",
        CourseLength = 3,
        CourseType = 2,
        CreatedAt = DateTime.Now,
        CreatedBy = "Instructor",
        ModifiedAt = DateTime.Now,
        ModifiedBy = "Instructor"
      };
      var Course3 = new DummyCourse()
      {
        CourseId = 3,
        Name = "Programming Fundamentals",
        CourseLength = 4,
        CourseType = 1,
        CreatedAt = DateTime.Now,
        CreatedBy = "Teacher ",
        ModifiedAt = DateTime.Now,
        ModifiedBy = "Teacher Assistant"
      };
}

Upvotes: 1

Views: 86

Answers (4)

Mehmet Top&#231;u
Mehmet Top&#231;u

Reputation: 1364

Before create list instance ,after add your Course instances into list and return list

List<DummyCourse> dc=new List<DummyCourse>();
dc.Add(Course1);
dc.Add(Course2);
dc.Add(Course3);

return dc;

Upvotes: 0

Laoujin
Laoujin

Reputation: 10229

Instead of a list, you could also just return an IEnumerable<DummyCourse>:

IEnumerable<DummyCourse> GetDummyCoursesList()
{
     yield return new DummyCourse()
     {
        CourseId = 1,
     };
     yield return new DummyCourse()
     {
        CourseId = 2,
     };
     yield return new DummyCourse()
     {
        CourseId = 3,
     };
}

Upvotes: 0

Syed Md. Kamruzzaman
Syed Md. Kamruzzaman

Reputation: 1089

Try adding class object to list object then return

List<DummyCourse> dummyCourseList =new List<DummyCourse>();

dummyCourseList.Add(Course1);
dummyCourseList.Add(Course2);
dummyCourseList.Add(Course3);

return dummyCourseList ;

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156968

You have only created instances, but you never tell what to return. Use the return keyword and make explicit what you want to return: not just a few instances, but a new list consisting of the instances you have just created. (imaging you could just return a list with one of the courses: how would the compiler know which to pick?)

Place this at the end of your method:

return new List<DummyCourse>() { Course1, Course2, Course3 };

Upvotes: 3

Related Questions