Wizard
Wizard

Reputation: 1152

How to validate a null input

the problem I'm having is to validate the input means putting it in a try catch which then wont pass the variable through and I'm getting this error:

Use of unassigned local variable 'MainMenuSelection'

I've validated using this method before but for some reason it's not working now, please help

//Take the menu selection
try
{
    mainMenuSelection = byte.Parse(Console.ReadLine());
}
catch
{
    Console.WriteLine("Please enter a valid selection");
}


switch (mainMenuSelection) //Where error is shown

Upvotes: 1

Views: 911

Answers (3)

sll
sll

Reputation: 62494

Obviously user can input anything which would not be parsed as a single byte. Try out using Byte.TryParse() method which does not generate exception and just return status flag.

You can go further and add more analysis for an user input if needed:

// Initialize by a default value to avoid
// "Use of unassigned local variable 'MainMenuSelection'" error
byte mainMenuSelection = 0x00;    
string input = Console.ReadLine();

// If acceptable - remove possible spaces at the start and the end of a string
input = input.Trim();
if (input.Lenght > 1)
{
   // can you do anything if user entered multiple characters?
}
else
{
   if (!byte.TryParse(input, out mainMenuSelection))
   {
       // parsing error
   }
   else
   {
       // ok, do switch
   }
}

Also perhaps you just need a single character not a byte? Then just do:

// Character with code 0x00 would be a default value. 
// and indicate that nothing was read/parsed    
string input = Console.ReadLine();
char mainMenuSelection = input.Length > 0 ? input[0] : 0x00;

Upvotes: 1

Bryan Crosby
Bryan Crosby

Reputation: 6554

A better method would be to use byte.TryParse(). It's made specifically for these types of scenarios.

byte b;
if (byte.TryParse("1", out b))
{
    //do something with b
}
else
{
    //can't be parsed
}

Upvotes: 1

Ben
Ben

Reputation: 764

If you're just concerned about the input itself, you can use the Byte.TryParse Method and then handle the false boolean case instead.

byte mainMenuSelection;
if (Byte.TryParse(Console.ReadLine(), out mainMenuSelection)
{
    switch(mainMenuSelection);
}
else
{
    Console.WriteLine("Please enter a valid selection");
}

Upvotes: 0

Related Questions