Question

Aditya is a co-worker of yours at Company ABC. Aditya has a problem with his C# code caused by his use of Polymorphism. The code can be compiled but is throwing a runtime error as shown below. Could you help Aditya to figure out what is the reason? State what the problem is and add one line of code to correct the problem.

An unhandled exception of type System.InvalidCastException occurred in polymorphism.exe Additional information: Unable to c

C# Code:

class Sensor

    {

        private string sensorName;

        public Sensor(string _name)

        {

            sensorName = _name;

        }

        public virtual void ActionType()

        {

            Console.WriteLine("Sensor Detect Nothing.");

        }

}

class SmokeSensor : Sensor

    {

        private string type;

        public SmokeSensor(string _type, string _name) : base(_name)

        {

            type = _type;

        }

        public override void ActionType ()

        {

            Console.WriteLine("Somke Sensor Detect Smoke.");

        }

    }

class Program

    {

        static void Main(string[] args)

        {

            Sensor super1, super2;

            SmokeSensor sub1, sub2;

            super1 = new Sensor("Sensor");

            sub1 = new SmokeSensor("Smoke", "Smoke Sensor");

            super2 = super1;

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \\Tip: this is where the code should go.

            sub2 = (SmokeSensor)super1;

       }

    }

One line of code needs to be added to make this run correctly. How do I make it so (SmokeSensor)super1 can correctly be casted to sub2?

Thanks ;)

0 0
Add a comment Improve this question Transcribed image text
Answer #1


Problem:

Trying to convert object of type Sensor class(Base Class) to SmokeSensor class(Child Class). Which is illegal in C-Sharp.

Solution:

Applying Downcasting process will solve the problem.

Initially Base class object "super1" should be converted to SmokeSensor class Type as follows:

super1 = sub1;

___________________________________________________________________

Updated Code:

class Sensor
{
private string sensorName;
public Sensor(string _name)
{
sensorName = _name;
}

public virtual void ActionType()
{
Console.WriteLine("Sensor Detect Nothing.");
}
}

class SmokeSensor : Sensor
{
private string type;
public SmokeSensor(string _type, string _name) : base(_name)
{
type = _type;
}

public override void ActionType ()
{
Console.WriteLine("Somke Sensor Detect Smoke.");
}
}

class Program
{
static void Main(string[] args)
{
Sensor super1, super2;
SmokeSensor sub1, sub2;
super1 = new Sensor("Sensor");
sub1 = new SmokeSensor("Smoke", "Smoke Sensor");
super2 = super1;
  
//Downcasting by converting Sensor class object(Base Class Object) to SmokeSensor class object(Child class Object)
super1 = sub1;

  
sub2 = (SmokeSensor)super1;
}
}

____________________________________________________________________________________________

Sample Run:

Livec Run it (F8) Save it Show compiler warnings [ + ] Show input Compilation time: 0,14 sec, absolute running time: 0,14 sec

Add a comment
Know the answer?
Add Answer to:
Aditya is a co-worker of yours at Company ABC. Aditya has a problem with his C#...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The following code has a problem with polymorphism. I keep getting a runtime error. Error: "An...

    The following code has a problem with polymorphism. I keep getting a runtime error. Error: "An unhandled exception of type System.InvalidCastException occured in polymorphism.exe" Apparently, I need one line of code to fix it. C# Code: class Sensor     {         private string sensorName;         public Sensor(string _name)         {             sensorName = _name;         }         public virtual void ActionType()         {             Console.WriteLine("Sensor Detect Nothing.");         } } class SmokeSensor : Sensor     {         private string type;...

  • C# Hey I am having trouble implementing additonal function to this assignment: Problem: Implement three IComparer classes on Employee - NameComparer, AgeComparer, and PayComparer - that allow Employee...

    C# Hey I am having trouble implementing additonal function to this assignment: Problem: Implement three IComparer classes on Employee - NameComparer, AgeComparer, and PayComparer - that allow Employees to be compared by the Name, Age, and Pay, respectively. Code: Employee.Core.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Employees { partial class Employee { // Field data. private string empName; private int empID; private float currPay; private int empAge; private string empSSN = ""; private string empBene...

  • Hello in C#. I need help understanding and knwoing what i missed in my program. The...

    Hello in C#. I need help understanding and knwoing what i missed in my program. The issue is, the program is supposed to have user input for 12 family members and at the end of the 12 it asks for user to input a name to search for. When i put a correct name, it always gives me a relative not found message. WHat did i miss. And can you adjust the new code so im able to see where...

  • Can anyone identify which OO Design Patterns are being used in the following code?: package mis;...

    Can anyone identify which OO Design Patterns are being used in the following code?: package mis; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; class helpDeskGuidline{    private void setGuideLine(){           }    public void rateService(){           } } public class HelpDeskService extends helpDeskGuidline{ //HelpDeskService class extends helpDeskGuidline this    //called inheritance    private static int ticketId=1;    Ticket ticket; // HelpDeskService class using ticket class object. this is has-A relationship (aggregation)          ArrayList<Ticket> allTicket=new ArrayList<>();    HashMap<Ticket,Person> ticketAllocation=new HashMap<>();    HashMap<Person,Integer> assignee=new HashMap<>();    HelpDeskService(){        Person...

  • IN C# The fun for today is to build your own circular array to support a...

    IN C# The fun for today is to build your own circular array to support a queue. The challenge here is in adjusting your queueFront and queueRear markers (they are just integer array indices), and dealing with what happens when they wrap around the First/last element of the array. The tricky part here is worrying about the edge cases. There are only two methods you need to fix up addBack – this should correctly add an item at the rear...

  • I need help modifying this code please ASAP using C++ Here is what I missed on this code below Here are the instruction...

    I need help modifying this code please ASAP using C++ Here is what I missed on this code below Here are the instructions Here is the code Produce correct70 pts O pts Full Marks No Marks results and statisfy requirements view longer Comments 1. Your display amount is not readable 2. I withdraw more than my balance, but I didn't see any error message description Documentations10 pts 0 pts Full Marks No Marks : comment i code and block comment...

  • whats the answer When defining a class which has the field name of type String. How...

    whats the answer When defining a class which has the field name of type String. How is the name field declared? String nam name Opublic String name; private name; private String name; Given the following class definition, Which operation can a class user perform on an object of type Restaurant? public class Restaurant // Info about a restaurant // Internal fields public void setName(String restaurant Name) { // Sets the restaurant's name } public void setRating(int user Rating) { //...

  • Problem 1 1. In the src → edu.neiu.p2 directory, create a package named problem1. 2. Create...

    Problem 1 1. In the src → edu.neiu.p2 directory, create a package named problem1. 2. Create a Java class named StringParser with the following: • A public static method named findInteger that takes a String and two char variables as parameters (in that order) and does not return anything. • The method should find and print the integer value that is located in between the two characters. You can assume that the second char parameter will always follow the first...

  • Méalgomé, a techie blogger, has a good command of the english language and his typing skills...

    Méalgomé, a techie blogger, has a good command of the english language and his typing skills are quite good. As a conservative computer geek, he is stuck with a text editor that does not perform spell-check. He believes that even the spell checker of modern editors would not be able to let go of the technical words that do not appear in regular dictionaries. Moreover, his Page 2 of 5 one-off mistakes on his blogs are becoming a divergence when...

  • Hey I really need some help asap!!!! I have to take the node class that is...

    Hey I really need some help asap!!!! I have to take the node class that is in my ziplist file class and give it it's own file. My project has to have 4 file classes but have 3. The Node class is currently in the ziplist file. I need it to be in it's own file, but I am stuck on how to do this. I also need a uml diagram lab report explaining how I tested my code input...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT