C# How to loop user input until the datatype of the input is correct?

Solution 1:

while (!int.TryParse(Console.ReadLine(), out mynum))
    Console.WriteLine("Try again");

edit:

public void setX() {
    Console.Write("Enter a value for X (int): ");
    while (!int.TryParse(Console.ReadLine(), out x))
        Console.Write("The value must be of integer type, try again: ");
}

Try this. I personally prefer to use while, but do .. while is also valid solution. The thing is that I don't really want to print error message before any input. However while has also problem with more complicated input that can't be pushed into one line. It really depends on what exactly you need. In some cases I'd even recommend to use goto even tho some people would probably track me down and slap me with a fish because of it.

Solution 2:

Even though the question has been already marked as answered, do-while loops are much better for validating user input.

Notice your code:

Console.WriteLine("The value must be of integer type");
while (!int.TryParse(Console.ReadLine(), out temp2))
    Console.WriteLine("The value must be of integer type");

You have the same code at top and bottom. This can be changed:

do {
    Console.WriteLine("The value must be of integer type");
} while (!int.TryParse(Console.ReadLine(), out temp2));