Is Generics needed for this?
TIA

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

namespace VehicleWorld
{
    public class Car
    {
        private int topSpeed;

        public Car() { }

        public Car Select(int topSpeed)
        {
            Car c = new Car();
            c.topSpeed = topSpeed;
            return c;
        }

        public override string ToString()
        {
            return String.Format("Top speed for {0} is: {1}", this.GetType(), topSpeed.ToString());
        }
    }

    public class FastCar : Car
    {
        public FastCar() { }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            Car c = new Car();
            c = c.Select(60);
            Console.WriteLine(c.ToString());

            FastCar fc = new FastCar();  
            fc = fc.Select(100);  //ERROR here:  Cannot implicitly convert type 'VehicleWorld.Car' to 'VehicleWorld.FastCar'. An explicit conversion exists (are you missing a cast?)
            Console.WriteLine(fc.ToString());
        }
    }
}

Recommended Answers

All 2 Replies

Hi,

FastCar fc = new FastCar();
        Car c1 = fc;

will be ok.
but what you have done is opposite.
you can assign pointer of object of child class to pointer variable of parent class but cant do opposite directly.
Ex. Whole concept of Stream Zoo in this way.

Thanks, I knew it's something stupid on my part!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.