Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How do I add 3 objects to array in C#

How do I add 3 objects to array in C#

Scheduled Pinned Locked Moved C#
questioncsharpdata-structureslearning
12 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Aindriu Mac Giolla Eoin

    Hi, How can I add 3 objects to an array in C# ? I created 3 objects of a class and I want those three objects in an array in another class but I get the syntax wrong. here in the main method I created 3 objects from Class student

    static void Main(string\[\] args)
            {
    
             //  Create 3 students
                Student student1 = new Student
    
                {
                    FirstName = "John",
                    LastName = "Wayne",
                    BirthDate = "26/05/1907"
    
                };
    
                Student student2 = new Student
                {
                    FirstName = "Craig",
                    LastName = "Playstead",
                    BirthDate ="01/01/1967"
                };
    
                Student student3 = new Student
                {
                    FirstName = "Paula",
                    LastName = "Smith",
                    BirthDate = "01/12/1977"
                };
    

    In another class I want to create an array and put the 3 student objects into it, how do I do that ? So far I only created an array[3]

    Public class Course
            {
                private string courseName;
    
                public string CourseName
                {
                    get { return courseName; }
                    set { courseName = value; }
                }
    
    
                Student\[\] studentarray = new Student\[3\];
    
    S Offline
    S Offline
    Sascha Lefevre
    wrote on last edited by
    #2

    Very easy:

    Student[] studentarray = new Student[3];

    studentarray[0] = student1;
    studentarray[1] = student2;
    studentarray[2] = student3;

    If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

    A 1 Reply Last reply
    0
    • S Sascha Lefevre

      Very easy:

      Student[] studentarray = new Student[3];

      studentarray[0] = student1;
      studentarray[1] = student2;
      studentarray[2] = student3;

      If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

      A Offline
      A Offline
      Aindriu Mac Giolla Eoin
      wrote on last edited by
      #3

      thanks, i got the syntax mixed up ! **edit., i get lots of errors when I try this Error 1 Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

      S 1 Reply Last reply
      0
      • A Aindriu Mac Giolla Eoin

        thanks, i got the syntax mixed up ! **edit., i get lots of errors when I try this Error 1 Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

        S Offline
        S Offline
        Sascha Lefevre
        wrote on last edited by
        #4

        You're welcome! Consider using a generic List instead of an array (if you don't use an array on purpose for some reason). It's way more flexible, e.g. allows dynamic growth in contrast to an array. Would look like this:

        List<Student> students = new List<Student>();

        students.Add(student1);
        students.Add(student2);
        students.Add(student3);

        (put a using System.Collections.Generic; at the top of your source file.)

        If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

        A 1 Reply Last reply
        0
        • S Sascha Lefevre

          You're welcome! Consider using a generic List instead of an array (if you don't use an array on purpose for some reason). It's way more flexible, e.g. allows dynamic growth in contrast to an array. Would look like this:

          List<Student> students = new List<Student>();

          students.Add(student1);
          students.Add(student2);
          students.Add(student3);

          (put a using System.Collections.Generic; at the top of your source file.)

          If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

          A Offline
          A Offline
          Aindriu Mac Giolla Eoin
          wrote on last edited by
          #5

          its not letting me add the objects to the array created. studentarray[0] = student1; Error: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) I created the 3 objects (of another class called Student) in the main method, I don't know if I can add the three objects from there ?

          P S 2 Replies Last reply
          0
          • A Aindriu Mac Giolla Eoin

            its not letting me add the objects to the array created. studentarray[0] = student1; Error: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) I created the 3 objects (of another class called Student) in the main method, I don't know if I can add the three objects from there ?

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #6

            Please edit your question to include the code as you have it now, and the exact error message you are receiving.

            1 Reply Last reply
            0
            • A Aindriu Mac Giolla Eoin

              its not letting me add the objects to the array created. studentarray[0] = student1; Error: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) I created the 3 objects (of another class called Student) in the main method, I don't know if I can add the three objects from there ?

              S Offline
              S Offline
              Sascha Lefevre
              wrote on last edited by
              #7

              I assume you've put the assignment into the class-scope, like so (15th line or so):

              Public class Course
              {
              private string courseName;

              public string CourseName
              {
                  get { return courseName; }
                  set { courseName = value; }
              }
              
              // this would be ok, because it's a "declaration" like "private string courseName;" above
              Student\[\] studentarray = new Student\[3\]; 
              
              // this isn't a declaration and can't exist directly in the class scope:
              studentarray\[0\] = student1;
              
              // instead theoretically something like this (within a methods scope):
              public void SomeMethod()
              {
                  studentarray\[0\] = student1;
                  // "theoretically" because "student1" isn't known here
              }
              
              // makes a tiny bit more sense:
              public void SetStudent0(Student student)
              {
                  studentarray\[0\] = student;
                  // only a tiny bit because this method would have the fixed purpose
                  // of assigning to array index 0
              }
              // you would call it outside of this class like so: someCourse.SetStudent0(student1);
              
              // some more sense:
              public void SetStudent(Student student, int index)
              {
                  studentarray\[index\] = student;
                  // only some more sense because from outside this class you don't know which
                  // array indices would be valid
              }
              // you would call it outside of this class like so: someCourse.SetStudent(student1, 0);
              
              // even more sense:
              private int ArrayCursor = 0;
              public void AddStudent(Student student)
              {
                  studentarray\[ArrayCursor\] = student;
                  ArrayCursor++;
                  // will only work as long as there's enough space in the array
              }
              // you would call it outside of this class like so: someCourse.AddStudent(student1);
              
              // best with a generic list:
              private List<Student> Students = new List<Student>();
              public void AddStudent(Student student)
              {
                  Students.Add(student);
              }
              

              }

              If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

              A 1 Reply Last reply
              0
              • S Sascha Lefevre

                I assume you've put the assignment into the class-scope, like so (15th line or so):

                Public class Course
                {
                private string courseName;

                public string CourseName
                {
                    get { return courseName; }
                    set { courseName = value; }
                }
                
                // this would be ok, because it's a "declaration" like "private string courseName;" above
                Student\[\] studentarray = new Student\[3\]; 
                
                // this isn't a declaration and can't exist directly in the class scope:
                studentarray\[0\] = student1;
                
                // instead theoretically something like this (within a methods scope):
                public void SomeMethod()
                {
                    studentarray\[0\] = student1;
                    // "theoretically" because "student1" isn't known here
                }
                
                // makes a tiny bit more sense:
                public void SetStudent0(Student student)
                {
                    studentarray\[0\] = student;
                    // only a tiny bit because this method would have the fixed purpose
                    // of assigning to array index 0
                }
                // you would call it outside of this class like so: someCourse.SetStudent0(student1);
                
                // some more sense:
                public void SetStudent(Student student, int index)
                {
                    studentarray\[index\] = student;
                    // only some more sense because from outside this class you don't know which
                    // array indices would be valid
                }
                // you would call it outside of this class like so: someCourse.SetStudent(student1, 0);
                
                // even more sense:
                private int ArrayCursor = 0;
                public void AddStudent(Student student)
                {
                    studentarray\[ArrayCursor\] = student;
                    ArrayCursor++;
                    // will only work as long as there's enough space in the array
                }
                // you would call it outside of this class like so: someCourse.AddStudent(student1);
                
                // best with a generic list:
                private List<Student> Students = new List<Student>();
                public void AddStudent(Student student)
                {
                    Students.Add(student);
                }
                

                }

                If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                A Offline
                A Offline
                Aindriu Mac Giolla Eoin
                wrote on last edited by
                #8

                using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace Assignment5 { class Program { static void Main(string[] args) { // Create 3 students Student student1 = new Student { FirstName = "John", LastName = "Wayne", BirthDate = "26/05/1907" }; Student student2 = new Student { FirstName = "Craig", LastName = "Playstead", BirthDate ="01/01/1967" }; Student student3 = new Student { FirstName = "Paula", LastName = "Smith", BirthDate = "01/12/1977" }; // Create Teacher Teacher teacher1 = new Teacher { TeacherfirstName = "Paul", }; // Create course object Course course = new Course(); course.CourseName = "Programming with C#."; // Create degree object Degree degree = new Degree(); degree.DegreeName = "Bachelor of Science Degree"; // Create Program object UProgram uprogram = new UProgram(); uprogram.ProgramName = "Information Technology"; // count = GetActiveInstances(typeof(Student)); Console.WriteLine("The {0} program contains the {1} ", uprogram.ProgramName, degree.DegreeName); Console.WriteLine("The {0} contains the course {1} ",degree.DegreeName, course.CourseName ); // Console.WriteLine("The {0} course contains students(s)" count); Console.WriteLine("Count" + Student.count); Console.Read(); } public class Student { public static int count = 0; public Student() { // Thread safe since this is a static property Interlocked.Increment(ref count); } // use properties! private string firstName; // Get Set for FirstName public string FirstName { get { return firstName; } set { firstName = value; } }

                S 1 Reply Last reply
                0
                • A Aindriu Mac Giolla Eoin

                  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace Assignment5 { class Program { static void Main(string[] args) { // Create 3 students Student student1 = new Student { FirstName = "John", LastName = "Wayne", BirthDate = "26/05/1907" }; Student student2 = new Student { FirstName = "Craig", LastName = "Playstead", BirthDate ="01/01/1967" }; Student student3 = new Student { FirstName = "Paula", LastName = "Smith", BirthDate = "01/12/1977" }; // Create Teacher Teacher teacher1 = new Teacher { TeacherfirstName = "Paul", }; // Create course object Course course = new Course(); course.CourseName = "Programming with C#."; // Create degree object Degree degree = new Degree(); degree.DegreeName = "Bachelor of Science Degree"; // Create Program object UProgram uprogram = new UProgram(); uprogram.ProgramName = "Information Technology"; // count = GetActiveInstances(typeof(Student)); Console.WriteLine("The {0} program contains the {1} ", uprogram.ProgramName, degree.DegreeName); Console.WriteLine("The {0} contains the course {1} ",degree.DegreeName, course.CourseName ); // Console.WriteLine("The {0} course contains students(s)" count); Console.WriteLine("Count" + Student.count); Console.Read(); } public class Student { public static int count = 0; public Student() { // Thread safe since this is a static property Interlocked.Increment(ref count); } // use properties! private string firstName; // Get Set for FirstName public string FirstName { get { return firstName; } set { firstName = value; } }

                  S Offline
                  S Offline
                  Sascha Lefevre
                  wrote on last edited by
                  #9

                  Yes - it's what I assumed it my last reply :) You inserted the assignment to array-index 0 directly within class-scope. It has to happen in a method (or, theoretically, in the constructor).

                  If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                  A 1 Reply Last reply
                  0
                  • S Sascha Lefevre

                    Yes - it's what I assumed it my last reply :) You inserted the assignment to array-index 0 directly within class-scope. It has to happen in a method (or, theoretically, in the constructor).

                    If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                    A Offline
                    A Offline
                    Aindriu Mac Giolla Eoin
                    wrote on last edited by
                    #10

                    thanks for the post ! I will create a method and increment through the 3 students and add them, i will call the method outside the class

                    S 1 Reply Last reply
                    0
                    • A Aindriu Mac Giolla Eoin

                      thanks for the post ! I will create a method and increment through the 3 students and add them, i will call the method outside the class

                      S Offline
                      S Offline
                      Sascha Lefevre
                      wrote on last edited by
                      #11

                      tá fáilte romhat :)

                      If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                      A 1 Reply Last reply
                      0
                      • S Sascha Lefevre

                        tá fáilte romhat :)

                        If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                        A Offline
                        A Offline
                        Aindriu Mac Giolla Eoin
                        wrote on last edited by
                        #12

                        an-mhaith !!:thumbsup:

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups