How to add two numbers using Console.ReadLine()


I want to add two numbers using Console.ReadLine(), but it gives me the error

Invalid expression term 'int'

Here is my code:

using System;

namespace MyApplication
  class Program
    static void Main(string[] args)
      Console.WriteLine("Enter a number:");
      string number1 = Console.ReadLine();
      Console.WriteLine("Enter another number:");
      string number2 = Console.ReadLine();
      Console.WriteLine("The sum of those numbers is:");
      Console.WriteLine(int(number1) + int(number2));

Could you help?

>Solution :

Use the Convert.ToInt32() method to convert from string to int.

Console.WriteLine(Convert.ToInt32(number1) + Convert.ToInt32(number2));

See How can I convert String to Int? for more examples or alternatives.

Note: You write

string s = "42";
int i = int(s); // Compiler error Invalid Expression term

This syntax is used for type casting in languages like Pascal or Python. But in C based languages like C#, C++ or Java you use a different syntax:

string s = "42";
int i = (int)s; // Compiler error invalid cast

Round brackets around the type name, not around the value. This will still not work, though, because there is no direct cast from type string to type int in C#. It would work for different types:

double d = 42d;
int i = (int)d; // Works

Leave a ReplyCancel reply