Here there are 2 classes Employee(base class) and Manager(sub class) Manager inherits from Employee.I have added 2 Interfaces IName and ISalary so that i can downcast.
interface IName
{
string Name { get; }
void MyName();
}
interface ISalary
{
string Salary { get; }
void MySalary();
}
class Employee : IName
{
public Employee (string name)
{
this.name = name;
}
private string name;
public string Name
{
get { return " My name is " + name; }
}
public void MyName()
{
MessageBox.Show(this.Name);
}
}
class Manager : Employee, ISalary
{
public Manager(string name, int salary) : base(name)
{
this.salary = salary;
}
private int salary;
private int name;
public string Salary
{
get { return name + " Salary : " + salary + " per month"; }
}
public void MySalary()
{
MessageBox.Show(this.Salary);
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Manager[] manager = new Manager[2];
manager[0] = new Manager("Joe", 400);
manager[1] = new Manager("John", 500);
Employee[] employee = manager;
ISalary someemployee = employee as Manager;
someemployee.MySalary();
}
}
Here are the errors that i'm getting
Cannot convert type 'WindowsFormsApplication26.Employee[]' to 'WindowsFormsApplication26.Manager' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
When downcasting the conversion returns to null.
Also Under manager class i have to mention the line
private string name ;
despite using the base keyword in the constructor above it. Otherwise the name parameter is not recognized by the class.
Question
Ch33f
Here there are 2 classes Employee(base class) and Manager(sub class) Manager inherits from Employee.I have added 2 Interfaces IName and ISalary so that i can downcast.
Here are the errors that i'm getting
Cannot convert type 'WindowsFormsApplication26.Employee[]' to 'WindowsFormsApplication26.Manager' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
When downcasting the conversion returns to null.
Also Under manager class i have to mention the line
private string name ;
despite using the base keyword in the constructor above it. Otherwise the name parameter is not recognized by the class.
Link to comment
https://www.neowin.net/forum/topic/1322268-upcasting-and-downcasting-an-array/Share on other sites
3 answers to this question
Recommended Posts