3 Replies - 285 Views - Last Post: 06 March 2013 - 12:11 PM Rate Topic: -----

#1 ray1234  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 147
  • Joined: 07-September 12

I want to call derived methods in base type variable

Posted 06 March 2013 - 11:42 AM

i want my base type variable to be assigned a derived type, and then call the new functionality in the dervived on my base type variable, how can i do this.

Ray


 public class baseclass
    {
        

        public void eat()
        {
            Console.WriteLine("eat");
        }
    }

    public class derivedclass : baseclass
    {
        public void sleep()
        {
            Console.WriteLine("sleep");
        }

        public void drink()
        {
            Console.WriteLine("drink");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            baseclass cl = new baseclass()
            cl.sleep()
            c1.drink()       // i want base variable c1 to have derive functionality. is there  a way i can do this.
            
        }
    }



This post has been edited by ray1234: 06 March 2013 - 11:44 AM


Is This A Good Question/Topic? 0
  • +

Replies To: I want to call derived methods in base type variable

#2 Ryano121  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1362
  • View blog
  • Posts: 3,002
  • Joined: 30-January 11

Re: I want to call derived methods in base type variable

Posted 06 March 2013 - 11:57 AM

Yes look into overriding methods.

Polymorphism (especially the bit about virtual methods and overriding them).
Was This Post Helpful? 0
  • +
  • -

#3 darek9576  Icon User is offline

  • D.I.C Lover

Reputation: 198
  • View blog
  • Posts: 1,682
  • Joined: 13-March 10

Re: I want to call derived methods in base type variable

Posted 06 March 2013 - 11:58 AM

Your Base Class has no idea about it's children.
Was This Post Helpful? 0
  • +
  • -

#4 lordofduct  Icon User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2531
  • View blog
  • Posts: 4,631
  • Joined: 24-September 10

Re: I want to call derived methods in base type variable

Posted 06 March 2013 - 12:11 PM

In the example code 'Ray' instantiates a 'baseclass'. So your object isn't a 'derivedclass', and thusly doesn't have the functionality of 'derivedclass'.

You need it to be a 'derivedclass' first off.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1