Aditya Arora Aditya Arora -4 years ago 99
C# Question

C# - invalid outputs

I am using

enums
in C# to calculate the areas of different shapes. Below is my code:

using System;
class Area
{
public enum Shape{Circle,Square};
public void AreaShape(int x,Shape ob1)
{
double a;
switch(x)
{
case (int)Shape.Circle:
a=Math.PI*x*x;
Console.WriteLine("Circle "+a);
break;
case (int)Shape.Square:
a=x*x;
Console.WriteLine("Square "+a);
break;
default:
Console.WriteLine("Invalid");
break;
}
}
}
class MyTestOne
{
public static void Main(String[] a)
{
Area obj1=new Area();
obj1.AreaShape(15,Area.Shape.Circle);
obj1.AreaShape(15,Area.Shape.Square);
}
}


The following produces an error:

obj1.AreaShape(15,Shape.Circle);
obj1.AreaShape(15,Shape.Square);


How can I get the following output?

Circle 225*pi
Square 225


When I use
Area.Shape.Circle
and
Area.Shape.Square
, the output is:

Invalid
Invalid

Answer Source

Pass Shape enum class not int x variable

            switch (ob1)
            {
                case Shape.Circle:
                    a = Math.PI * x * x;
                    Console.WriteLine("Circle " + a);
                    break;
                case Shape.Square:
                    a = x * x;
                    Console.WriteLine("Square " + a);
                    break;
                default:
                    Console.WriteLine("Invalid");
                    break;
            }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download