Wizard
Wizard

Reputation: 1162

Validating a console input

My mind has gone completely blank as to how to validate a null text value

All I need to do is check if an entered value is blank, if so ask again without continuing.

Console.WriteLine("Venue Name - ");
String venName = Console.ReadLine();

I can think how to do it with various loops and IF statements, but I'm sure there's a far more efficient way, please help.

Upvotes: 2

Views: 2947

Answers (5)

mark1982_fl
mark1982_fl

Reputation: 11

This is my first post, and I'm pretty new to c#, but here's another way to do it with a method call, which could be used for any such validation instead of writing redundant code:

string venName = null;
WriteName(venName);

public static void WriteName(string name)
{
    while(String.IsNullOrEmpty(name))
    {
         Console.WriteLine("Venue name - ");
         name = Console.ReadLine();
    }
}

Upvotes: 0

Bryan Crosby
Bryan Crosby

Reputation: 6554

If you are using .NET 4.0 you can use String.IsNullOrWhiteSpace() to check and see if the input is null, blank, or consists of all whitespace characters. Depending on your use-case this may be beneficial.

Upvotes: 0

gilly3
gilly3

Reputation: 91677

Not sure how or why you would do it without a loop or an if statement. Try this:

String venName = null;
while (String.IsNullOrEmpty(venName)) {
    Console.WriteLine("Venue Name - ");
    venName = Console.ReadLine();
}

Upvotes: 3

Khan
Khan

Reputation: 18172

if (!String.IsNullOrEmpty(venName))
{
    //Do Something
}

Upvotes: 0

Adam S
Adam S

Reputation: 3125

Use String.IsNullOrEmpty(venName) to check the user input.

Upvotes: 1

Related Questions