2
Answers

Significant of code position

Maha

Maha

17y
2.1k
1

Hi Guys

 

Significant of code position

 

I simplified the following program to conform to my problem. Program is producing same result like original one though code student[x] = new Student(); position is changed. I wish to know whether there is any importance of code position in the following program. Any one knows, please explain.

 

Thank you

 

Original one

 

using System;

public class StudetArrayDemo

{

    public static void Main()

    {

        Student[] student = new Student[2];

        int x;

        string enteredData;

        int enteredId;

 

        for (x = 0; x < student.Length; ++x)

            student[x] = new Student();   //going to shift

 

        for (x = 0; x < student.Length; ++x)

        {

            Console.Write("Enter ID for student #{0} ", x + 1);

            enteredData = Console.ReadLine();

            enteredId = Convert.ToInt32(enteredData);

            student[x].SetId(enteredId);

 

        }

 

        Console.WriteLine("------------------------------");

 

        for (x = 0; x < student.Length; ++x)

            Console.WriteLine("Student #{0} ID is {1}",

                x + 1, student[x].GetId());

    }

}

class Student

{

    private int idNumber;

 

    public int GetId()

    {

        return idNumber;

    }

 

    public void SetId(int id)

    {

        idNumber = id;

    }

}

 

Code student[x] = new Student(); position is shifted

 

using System;

public class StudetArrayDemo

{

    public static void Main()

    {

        Student[] student = new Student[2];

        int x;

        string enteredData;

        int enteredId;

 

        //for (x = 0; x < student.Length; ++x)

            //student[x] = new Student();

 

        for (x = 0; x < student.Length; ++x)

        {

            student[x] = new Student();   //shifted  

 

            Console.Write("Enter ID for student #{0} ", x + 1);

            enteredData = Console.ReadLine();

            enteredId = Convert.ToInt32(enteredData);

            student[x].SetId(enteredId);

 

        }

 

        Console.WriteLine("------------------------------");

 

        for (x = 0; x < student.Length; ++x)

            Console.WriteLine("Student #{0} ID is {1}",

                x + 1, student[x].GetId());

    }

}

class Student

{

    private int idNumber;

 

    public int GetId()

    {

        return idNumber;

    }

 

    public void SetId(int id)

    {

        idNumber = id;

    }

}

Answers (2)