• 0

Upcasting and Downcasting an Array


Question

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.

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

  • 0
Employee[] employee = manager;
ISalary someemployee = employee as Manager;

employee is an array. someemployee is not an array. You're trying to assign a collection of values to a single value, which makes no sense. Maybe you meant:

 

Employee[] employee = manager;
ISalary someemployee = employee[0]; // get the first employee in the array

And that doesn't make sense either, because Employee doesn't implement ISalary. The compiler won't let you do that, and trying to work around the compiler error with a cast will just turn the compile-time problem into a run-time problem. You could do:

 

Employee[] employee = manager;
ISalary someemployee = employee[0] as Manager; // get the first employee in the array

And incidentally, in this case, it won't fail at run-time, because you've actually only put Manager objects in that Employee array, and Manager implements ISalary. But this is terrible. If you ever put an actual Employee in that Employee array, the code will fail.

 

In general, casting arrays is bad, don't do it. It's in C# because C# copied Java without thinking on that point.

 

It's unclear what you're trying to do and why you need casts at all (or even arrays or even any class besides the form here). But at least this is explanation of what's wrong with your code.

 

  Quote

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.

Expand  

Because it's private in the base class. "private" means that it's only visible to that class and nothing else, including derived classes. If you want it to be visible in derived classes you need it to be "protected".

 

Realize that adding private string name ; in the Manager class means the Manager class now has two fields called name: one only visible in the base class and one only visible in the derived class, each with its own value. This is very confusing and definitely not what you want.

  • 0
  On 13/02/2017 at 20:41, Andre S. said:
Employee[] employee = manager;
ISalary someemployee = employee as Manager;

employee is an array. someemployee is not an array. You're trying to assign a collection of values to a single value, which makes no sense. Maybe you meant:

 

Employee[] employee = manager;
ISalary someemployee = employee[0]; // get the first employee in the array

And that doesn't make sense either, because Employee doesn't implement ISalary. The compiler won't let you do that, and trying to work around the compiler error with a cast will just turn the compile-time problem into a run-time problem. You could do:

 

Employee[] employee = manager;
ISalary someemployee = employee[0] as Manager; // get the first employee in the array

And incidentally, in this case, it won't fail at run-time, because you've actually only put Manager objects in that Employee array, and Manager implements ISalary. But this is terrible. If you ever put an actual Employee in that Employee array, the code will fail.

 

In general, casting arrays is bad, don't do it. It's in C# because C# copied Java without thinking on that point.

 

It's unclear what you're trying to do and why you need casts at all (or even arrays or even any class besides the form here). But at least this is explanation of what's wrong with your code.

 

Because it's private in the base class. "private" means that it's only visible to that class and nothing else, including derived classes. If you want it to be visible in derived classes you need it to be "protected".

 

Realize that adding private string name ; in the Manager class means the Manager class now has two fields called name: one only visible in the base class and one only visible in the derived class, each with its own value. This is very confusing and definitely not what you want.

Expand  

Ok i changed the code as you mentioned and i was able to get the output, So if i want the variables of employee[1] to be displayed do i need to create another instance of  ISalary like

 

ISalary someotheremployees = employee[1] as Manager;

someotheremployee.MySalary(); 

 

or is there another way of representing employee[0] and employee[1]  in a single line so that the output message box displays  both of their values one after the other

 

  • 0
  On 14/02/2017 at 13:14, Ch33f said:

Ok i changed the code as you mentioned and i was able to get the output, So if i want the variables of employee[1] to be displayed do i need to create another instance of  ISalary like

 

ISalary someotheremployees = employee[1] as Manager;

someotheremployee.MySalary(); 

 

or is there another way of representing employee[0] and employee[1]  in a single line so that the output message box displays  both of their values one after the other

Expand  

The basic problem is that you have 2 Managers you want to display, but for some reason, you insist on storing them inside an Employee array, only to be forced to cast them back to Managers (a perilous operation, as I mentioned) before displaying them.

 

This begs the question: why store them in an Employee array at all? Why not just use your original Manager array? It's unclear why you're doing things this way.

 

By the way you are not "creating another instance of ISalary" with the code you showed. You are creating another variable pointing to the same instance.

 

If you want to display the values of the array one after the other, just use a loop to go through the array (ex.: foreach).

This topic is now closed to further replies.
  • Posts

    • @Raze Bold it boy. (I admit, we all did it from time to time..)
    • Fan Control V227 by Razvan Serea Fan Control is a powerful and versatile portable utility that allows you to monitor, control and customize the fans of your GPU and CPU to keep your machine cool and running smoothly. Fan Control supports a wide range of devices and hardware configurations, giving you complete control over your computer's cooling system. Fan Control backend is mainly based on LibreHardwareMonitor, an open source fork of the original OpenHardwareMonitor. This means that hardware compatiblity is entirely open for anyone to contribute, and doesn't rely on a single developer who may stop caring at some point. Combined with the plugin system, Fan Control is unlocked for many generations of hardware to come. Main features Guided setup process on first launch Save, edit and load multiple profiles Change the theme and color of the application. Multiple temperature sources ( CPU, GPU, motherboard, hard drives... ) Multiple fan curve functions, including a custom graph Mix fan curves or sensor togethers (max, min, average) Low resource usage Advanced tuning with steps, start %, stop %, response time and hysteresis FanControl V227 changelog: Allow decimal with hysteresis values Radeon Pro support through ADLX Fix a bug when cancelling the graph editing dialog Update LibreHardwareMonitorLib Download: FanControl V227 | Installer ~15.0 MB (Open Source) View: Fan Control Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Lol tf you are talking about. People are PAYING by using this app exclusively, just indirectly. Do you have any idea how much facebook charges for api access to WhatsApp which has become more or less a monopoly in e-commerce.
    • My kid tried, so I took her to Microcenter and showed her the differences in price as well as storage and specs. We bought a Windows machine. She loves it, and is off to college this fall with her gaming level windows laptop at the price of a Mac that came with a 512GB SSD, and half the RAM.
    • Hasleo Backup Suite Free 5.4.2.1 by Razvan Serea Hasleo Backup Suite Free is a free Windows backup and restore software, which embeds backup, restore and cloning features, it is designed for Windows operating system users and can be used on both Windows PCs and Servers. The backup and restore feature of Hasleo Backup Suite can help you back up and restore the Windows operating systems, disks, partitions and files (folders) to protect the security of your Windows operating system and personal data. The cloning feature of Hasleo Backup Suite can help you migrate Windows to another disk, or easily upgrade a disk to an SSD or a larger capacity disk. System Backup & Restore / Disk/Partition Backup & Restore Backup Windows operating system and boot-related partitions, including user settings, drivers and applications installed in these partitions, which ensures that you can quickly restore your Windows operating system once it crashes. Viruses, power failure, or other unknown reasons may cause data loss, so it is a good habit to regularly back up the drive that stores important files, you can at least recover lost files from the backup image files in the event of a disaster. System Clone / Disk Clone / Partition Clone Migrate the Windows operating system from one disk to another SSD or larger disk without reinstalling Windows, applications and drivers. Clone entire disk to another disk and ensure that the contents of the source disk and the destination disk are exactly the same. Clone a partition completely to the specified location on the current disk or another disk and ensure that the data will not be changed. File Backup & Restore Back up specified files(folders) instead of the entire drive to another location to protect your data, so you can quickly restore files(folders) from the backup image files when needed. Incremental/Differential/Full Backup Different backup modes are supported, you can flexibly choose data protection schemes, which can improve backup performance and save storage space while ensuring data security. Delta Restore Delta restore uses advanced delta detection technology to check the changed blocks on the destination drive and restore only the changed blocks, so it has a faster restore speed than the traditional full restore. Universal Restore This feature can help us restore the Windows operating system to computers with different hardware and ensure that Windows can work normally without any hardware compatibility issues. Hasleo Backup Suite 5.4.2.1 changelog: The program crashes when sending emails Application notifications cannot be displayed in the Windows Notification Center Updated Italian and German translations Fixed other minor bugs Download: Hasleo Backup Suite 5.4.2.1 | 33.9 MB (Freeware) Links: Hasleo Backup Suite Website | Hasleo Backup Suite Guide | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Contributor
      GravityDead went up a rank
      Contributor
    • Week One Done
      BlakeBringer earned a badge
      Week One Done
    • Week One Done
      Helen Shafer earned a badge
      Week One Done
    • First Post
      emptyother earned a badge
      First Post
    • Week One Done
      Crunchy6 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      660
    2. 2
      ATLien_0
      266
    3. 3
      Michael Scrip
      235
    4. 4
      Steven P.
      164
    5. 5
      +FloatingFatMan
      150
  • Tell a friend

    Love Neowin? Tell a friend!