Shan Shan - 10 days ago 6
C# Question

CalculateArea using poymorphism and virtual method

I am trying to create a program to calculate the Area of different shapes using polymorphism using virtual and override method to their respective class.

I have done the coding as below:

class Program
{
static void Main(string[] args)
{
int side = 0;
Console.WriteLine("For what shape you want to calculate the Area:\n1. Square\n2. Rectangle\n3. Triangle\n4. Circle");
Console.Write("Please Select the number from above options: ");
int choice = int.Parse(Console.ReadLine());



switch (choice)
{
case 1:
Console.Write("Please enter the side of square: ");
side = int.Parse(Console.ReadLine());
return;

default:
Console.WriteLine("Incorrect Choice, please try again!");
break;
}

CalculateArea Sqa = new Square();
Sqa.Area(side);
Sqa.ShowResult();
}
}


But my code is not reaching to the point where I am creating object of Square Class, and it is coming out of the main method after switch case. Can anyone please let me know what is happening here?
To calculate and show the Area I have written below code.


class CalculateArea
{
public double result;
public virtual void Area(double side)
{
}
public void ShowResult()
{
Console.WriteLine($"Your Result is {result}");
}
}
class Square: CalculateArea
{

public override void Area(double side)
{
result = side * side;
}

}


Also I want to use properties to get and set the value for each shape but unable to do so (Getting unnecessary errors) because of lack of understanding of polymorphism behavior with properties.

As per my understanding in polymorphism we create variable of Base Class and then we create object of derive class. As I have created in my example

CalculateArea Sqa = new Square();


And if we create object like this, then only we can control the methods and variable of Base class.

Can anyone please refactor the above code to calculate area using polymophism (Virtual & Override Method) + Properties. Also please explain it and what I am missing in above code (I know above code is pathetic but I am not trying to figure it out correctly :( ).

Many Thanks.

Answer

Inside the switch statement, after case 1, your program will exit. This is because you have used return;, you might have intended to use break; instead. Break statement ensures that your switch wont fall through to the next statement, and a return statement would terminate the execution immediately.

Correct case statement should be like this

case 1:
    Console.Write("Please enter the side of square: ");
    side = int.Parse(Console.ReadLine());
    break;