Home > Back-end >  Casting inherited class on base class reference
Casting inherited class on base class reference

Time:06-24

How can I access the fields of object of inherited class through base class reference using casting?

For example, how can I access the grade field in SpecificStudent class?

The casting that I try here does not work.

Thanks!

namespace ConsoleApp4
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student[] students = new Student[2];

            students[0].name = "somename";

            students[1].name = "anothersomename";
            
            students[1] = (SpecificStudent)students[1];
            // students[1].grade         //This is what I want to be able to do

        }
        class Student
        {
            public string name;
        }
        class SpecificStudent:Student
        {
            public string grade;
            
        }
    }
}

CodePudding user response:

use casting directly

((SpecificStudent)students[1]).grade 

CodePudding user response:

Have you tried this?

        static void Main(string[] args)
        {
            Student[] students = new Student[2];

            students[0].name = "somename";

            students[1].name = "anothersomename";

            Console.WriteLine(((SpecificStudent)students[1]).grade);

        }
        class Student
        {
            public string name;
        }
        class SpecificStudent : Student
        {
            public string grade;

        }

If you equal student[1] to (SpecificStudent)student[1] you are recasting the specific into Student again since your array is of type Student. If you want you can use it directly or create another array

  • Related