13.5k views
4 votes
In C# Write and test a generic method that can be used to get a double value from the user. It should verify that the value entered by the user is a double and is within the acceptable range and force the user to continue entering data until the input is correct.

1 Answer

2 votes

Final answer:

To write a generic method in C# that gets a double value from the user and verifies its correctness and range, use the provided code.

Step-by-step explanation:

To write a generic method in C# that gets a double value from the user, you can use the following code:

public static T GetDoubleValue<T>() where T : struct, IConvertible
{
while (true)
{
Console.WriteLine("Enter a double value:");
string input = Console.ReadLine();

if (double.TryParse(input, out double result) && result >= 0 && result <= 100)
{
return (T)Convert.ChangeType(result, typeof(T));
}
else
{
Console.WriteLine("Invalid input! Please enter a valid double value between 0 and 100.");
}
}
}

This method uses the `TryParse` method to check if the input can be successfully parsed as a double. It also checks if the value is within the acceptable range of 0 to 100. The user will be prompted to enter a new value until a valid input is provided.

User Mark Nielsen
by
8.0k points