EN VI

Reading object value from other class in C#?

2024-03-16 12:00:08
How to Reading object value from other class in C#

I always have coded in C++ but I am learning C# now. I got a trouble with accessing the object value.

Here is what I tried.

class Program
{         
    static void Main(string[] args)
    {
        StudentInfo[] student = new StudentInfo[2];

        student[0] = new StudentInfo(100, 4);
        student[1] = new StudentInfo(101, 3);

        Trying ty = new Trying();
        ty.trial(); /// I got trouble with this line
    }
}
class Trying
{
    StudentInfo[] student = new StudentInfo[2]; // I added this line since it prevents compiler error
    public void trial()
    {   
        Console.WriteLine(student[1].Gpa); // I got trouble with this line
    }
}
class StudentInfo
{        
    public int studentNo {get; set;}
    public int Gpa {get; set;}
    public StudentInfo(int cc, int ct)
    {
        studentNo = cc;
        Gpa = ct;
    }
}

The error says

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.

How can I access the value student[1].Gpa correctly in the class Trying?

Solution:

The student in your main is NOT connected to the student in your Trying. You can disregard student code in your main. In Trying You did initialize an array but not added any objects. Array of nulls. See in comments how to fix it

class Trying
{
    StudentInfo[] students = new StudentInfo[2]; // <-- init array of nulls 

    // option 1 - init in constructor
    public Trying()
    {
        // option 1
        students[0] = new StudentInfo(1, 1); 
        students[1] = new StudentInfo(2, 2);
        students[2] = new StudentInfo(3, 3);
    }

    

    // option 2 - init in class declatrations
    StudentInfo[] students = new StudentInfo[] 
    {
        new StudentInfo(1, 1),
        new StudentInfo(2, 2),
        new StudentInfo(3, 3)
    };
  
    public void trial()
    {   
        Console.WriteLine(student[1].Gpa); // I got trouble with this line
    }
}

Ideal code

class Trying
{
    private StudentInfo[] students = new StudentInfo[] 
    {
        new StudentInfo(1, 1),
        new StudentInfo(2, 2),
        new StudentInfo(3, 3)
    };
  
    public void trial()
    {   
        Console.WriteLine(students[1].Gpa); // I got trouble with this line
    }
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login