anam
anam

Reputation: 216

How to call a method into a constructor in the same class and pass user input into this?

I found few posts on here quite similar to my question. But that's not helping. I want to calculate area of a circle. Rather than passing value by myself I want to take user input hence I created a method called myValue(). Now I want to call that method or int _radius variable into a constructor. I am new to C# and like your advice on this:

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;

            namespace PracticeFor70_483Exam.Venkat
            {
                class Circle
                {
                    private readonly int Radius;

                    public static int MyValue()
                    {
                        Console.WriteLine("Please enter radius value: ");
                        return Convert.ToInt32(Console.ReadLine());
                    }

                    float _PI = 3.141F;
                    public Circle()
                    {
                        Radius = myValue();
                        //this._radius = Radius; 
                    }
                    public float CalculateArea()
                    {
                        return this._PI * this.Radius * this.Radius;
                    }
                }
                class StaticAndInstanceClass
                {
                    public static void Main()
                    {
                        Circle c1 = new Circle(2);
                        float Area = c1.CalculateArea();
                        Console.WriteLine("The area is: {0}", Area);
                        Console.ReadLine();
                    }
                }
            }

Upvotes: 1

Views: 265

Answers (2)

Nikita Shrivastava
Nikita Shrivastava

Reputation: 3018

You have two problems in the given code:
1. myValue() instead of MyValue(). Since, it is case sensitive.
2. Circle(2) instead of Circle(). Since, it does not have a constructor that takes parameter.

Upvotes: 0

sara
sara

Reputation: 3589

Make the radius an instance field of the Circle class and modify the MyValue method.

public class Circle
{
    private readonly int Radius;

    public static int MyValue()
    {
        Console.WriteLine("Please enter radius value: ");
        return Convert.ToInt32(Console.ReadLine());
    }

    public Circle()
    {
        Radius = MyValue();
    }

...

}

Please note that this is a very "bad idea" though, your circle class should represent a circle and nothing else. Giving it information about the console is strange to say the least. It violates the Single Responsibility Principle among other things.

Upvotes: 2

Related Questions