0

im learning c# and i have problems with dynamic override , im trying to use and array of nations populed with different nation and if a specific nation appear i want to use a specific function of that class .

Abstract Class:

public abstract class Nazione
{
    int population;
    String name;

    public Nazione(int p, string n)
    {
        population = p;
        name = n;
    }

    public virtual int getPopulation() { return population; }

    public string getName() { return name; }
}

Overridden classes:

public class Italy : Nazione
{
    public Italy() : base (22391392,"Italia") {}
    public override int getPopulation()
    {
        return base.getPopulation();
    }
    public string Greetings() { return "Ciao"; }
}  

public class Germany : Nazione
{
    public Germany() : base(3428272,"Germania") { }
    public override int getPopulation()
    {
        return base.getPopulation()/2;
     }
}

Main:

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

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Nazione[] c = new Nazione[20];
            c[0] = new Italy();
            c[1] = new Germany();

            for (int i = 0; i < 2; i++)
            {
                if(c[i].getName()=="Italia")
                {
                   c[i].Greetings(); // this doesn't work :( 
                }
                Console.WriteLine(c[i].getPopulation());

            }
            Console.ReadKey();

        }
    }
}

I cannot call italy.Greetings() in runtime there is some scope error but i can't see it , thanks for your help .

2
  • 2
    Try (c[i] as Italy).Greetings(). Commented Aug 9, 2014 at 10:54
  • @HaZe Answer your question yourself and mark it as answer to help others having the same problem. The system will not allow you to mark as answer for 8 hours. So you can mark it later. Commented Aug 9, 2014 at 11:06

1 Answer 1

1

You can do the following in your example:

if(c[i].getName() == "Italia")
{
    ((Italy)c[i]).Greetings(); 
}

Or this is what I would do:

var italy = c[i] as Italy;
if(italy != null)
{
   italy.Greetings();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.