-2

I'm trying to write a program, and I want the program to read a line.

it is giving me this error

Cannot implicitly convert type 'string' to 'int

How can I convert the string to int? This is the part of the program that's giving the error.

class engineering : faculty
{
    public engineering()    \\constructor
    {
    }
    public int maths_grade;

    public override void fill_form()
    {
        Console.WriteLine("Insert Maths Grades: ");
        int maths_grade = Console.ReadLine();
    }
}
Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
Abzi94
  • 1
  • 1
  • 3
  • 1
    You can't assign string to an int. You have to Convert it. `int maths_grade = Convert.ToInt32(Console.ReadLine());` or Parse it using `int.TryParse` or `int.Parse`. Read about **[Casting and Type Conversions (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/ms173105.aspx)** – Habib Jul 04 '14 at 15:08
  • 1
    The return value of Console's ReadLine() is a string. You are trying to set maths_grade's value to a string. (but maths_grade is a defined as int!) So, in order to convert a string to an int you could use Convert.ToInt32(stringComesHere) or other method in the answers below. – Dominik Antal Jul 04 '14 at 15:12
  • 3
    If you are new to programming you should probably learn how to search for the errors you get before writing questions on Stackoverflow (I really think it will save you time). I can recommend [google](http://www.google.se) which finds 706 000 results based on your title. searching for [convert string to int](https://www.google.com/search?q=convert+string+to+int+c%23&oq=convert+string+to+&aqs=chrome.3.57j0j5j0j62j60.6910j0&sourceid=chrome&ie=UTF-8) gives 1 750 000 results. Take your pick – default Jul 04 '14 at 15:13

2 Answers2

0

You should use:

int maths_grade = int.Parse(Console.ReadLine());

because ReadLine returns string, then you need to parse it to get int. But this will throw an exception if line won't contain valid string (number). You can better check this by using TryParse version:

string line = Console.ReadLine();
int maths_grade;
if (!int.TryParse(line, out maths_grade))
{
    // Do some kind of error handling
}
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
0

Try

int mathsGrade;
if (int.TryParse(Console.ReadLine(), out mathsGrade))
{
     //Do something with grade
}
else
{
     //Do something to warn of invalid input.
}
Steve
  • 2,950
  • 3
  • 21
  • 32
  • Why has this been downvoted? It's a perfectly reasonable approach? – Steve Jul 04 '14 at 15:17
  • 3
    I suspect someone has been downvoting answers that are same as the first answer... whoever is doing this needs to stop. – Sayse Jul 04 '14 at 15:25