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 .
(c[i] as Italy).Greetings().