Search code examples
c#derived-class

I can't access a derived class method that is instantiated in an array


I was testing with some code and occasionally I can't access a method that is in a derived class.What could I be doing wrong?

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            A[] test = new A[2];
            test[0] = new B();
            test[0].Example();
            test[0].Example1();
        }
        public class A
        {
            public void Example()
            {

            }
        }
        class B : A
        {
            public void Example1()
            {

            }
        }
    }
}

Solution

  • You need to cast it to B type like this:

    namespace Example
    {
        class Program
        {
            static void Main(string[] args)
            {
                A[] test = new A[2];
                test[0] = new B();
                test[0].Example();
                (test[0] as B).Example1();
            }
            public class A
            {
                public void Example()
                {
    
                }
            }
            class B : A
            {
                public void Example1()
                {
    
                }
            }
        }
    }
    

    If you want to learn more about casting check the Docs.

    Edit: Casting works in this case because test[0] is of type B, if that wasn't the case the expression (test[0] as B) will return null which causes a NullReferenceException and means that test[0] cannot be casted to the type B.