Salim Latif Waigaonkar
Salim Latif Waigaonkar

Reputation: 472

How to access child class method in Parent class with different method name in C#

I want to access child class method in base class with different method name,am try to do with assigning ref of child class object to base class,but it shows error.

following is my sample code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Concepts
{
    class Parent 
    {
        public void display()
        {
            Console.WriteLine("I am in parent class");
        }
    }

    class children : Parent
    {
        public void displayChild()
        {
            Console.WriteLine("I am in child class");
        }
    }

    class Program 
    {
        static void Main(string[] args)
        {
            children child = new children();
            Parent par = new children();
            par.displayChild();
            child.display();
            child.displayChild();
            Console.ReadLine();
        }
    }
}

In above code par.displayChild(); shows an error.

Upvotes: 0

Views: 1286

Answers (2)

dbraillon
dbraillon

Reputation: 1752

As you create a Parent object with a new children instance you could cast it to children then use displayChild method.

class Program 
{
    static void Main(string[] args)
    {
        children child = new children();
        Parent par = new children();
        (par as children).displayChild();
        child.display();
        child.displayChild();
        Console.ReadLine();
    }
}

Upvotes: 0

Guy
Guy

Reputation: 50949

Parent par = new children(); creates new instance of children, but assign it to Parent variable. The variable type determines the methods and properties you can access. Parent doesn't have the method displayChild() so you are getting an error.

Upvotes: 1

Related Questions