1

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
2
  • can you show the definition of mainMenuSelection? Commented Mar 5, 2012 at 18:42
  • 1
    You really ought not to write catch without specifying the exception type. It's a bad habit that will bite you sooner or later. Commented Mar 5, 2012 at 18:55

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.