user4409948
user4409948

Reputation:

How can I TryParse() a string inputted by the user?

I have a C# program which takes a user input of a number (r.length = Console.ReadLine();), then calls Double.Parse(r.length);. However, I would like to use TryParse();, which returns false is it fails. So I have an if...else statement that outputs a message if there is an error. The conditional statement is as follows: if(Double.TryParse(Console.ReadLine, out r.length));. But converting a method group to a string is not allowed.

EDIT: As requested, here is a sample program demonstrating my problem:

using System;

namespace sample
{
    class sample
    {
        static void Main(string[] args)
        {
            double my_number;

            Console.WriteLine("Enter a number:");
            if(Double.TryParse(Console.WriteLine, out my_number))
            {}
            else
            {
                Console.WriteLine("Error: Expected number.");
            }
            Console.ReadKey();
        }
    }
}

Error: Argument '1': cannot convert from 'method group' to 'string' (CS1503)

So how can I work around this?

Upvotes: 1

Views: 513

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

A few things:

  1. Console.WriteLine writes the console. You need to use Console.ReadLine() method to read input string.
  2. Console does not have GetKey method. Sounds like you need ReadKey method.

    double my_number;
    
    Console.WriteLine("Enter a number:");
    if (Double.TryParse(Console.ReadLine(), out my_number))
    {
    
    }
    else
    {
        Console.WriteLine("Error: Expected number.");
    }
    Console.ReadKey();
    

Upvotes: 1

Richard Schneider
Richard Schneider

Reputation: 35477

if (!Double.TryParse(Console.ReadLine(), out my_number))
   Console.WriteLine("not a double.");

Upvotes: 3

Related Questions