How can I accept a ulong type variable in C#?

793 Views Asked by At

How can we take input of a ulong type variable in C#? if we use Console.ReadLine() then how to convert string to ulong ?

2

There are 2 best solutions below

1
jalsh On

Take a look at How to convert a string to a number

ulong res = ulong.Parse(Console.ReadLine());

0
ProgrammingLlama On

For number, boolean, and some other types, there are defined TryParse methods. These methods will take a string, and return a boolean (true if it was parsed successfully, false if it was unsuccessful) and the actual parsed value as an out parameter. It's strongly advisable to use these when dealing with user input or input that isn't guaranteed to be the type you're trying to parse.

This will avoid parse errors that would be thrown by ulong.Parse(Console.ReadLine()) if the input data isn't right, etc.

For example:

if (ulong.TryParse(Console.ReadLine(), out ulong parsedValue))
{
    Console.WriteLine($"You entered {parsedValue}.");
}
else
{
    Console.WriteLine("Please enter a valid value.");
}

See here for more info.