How to validate a null input - c#

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

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;

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
}

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

Related

How to control if someone is sending empty string to the decimal value?

I have a web service function which has a decimal value i.e. BRGEW.
Client is supposed to send the decimal value but he's sending string from SOAP UI and it's failing in conversion.
I have done this to control it but doesn't work.
if (General.BRGEW == 0 || General.BRGEW.ToString() == "") {
General.BRGEW =0;
}
How can I control this?
I guess you need String.IsNullOrEmpty(String) method
Check here
You can try this if you want to check that user input is decimal or not
var check= double.IsNaN(variable); //It will return boolean value after that add your code logic
First you need to check if the value is null or empty, if it is not null or empty then convert it.
decimal number;
string value = "";
if(!String.IsNullOrEmpty(value))
{
if(Decimal.TryParse(value, out number))
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
Console.WriteLine("Unable to convert '{0}'.", value);
}
}
if (General.BRGEW == 0)
{
General.BRGEW = 0;
}
doesn't change things much :) If RRGEW is already 0, then setting it to zero will have little effect.
A. Make the client send the number
This would be the easiest solution.
B. Deal with it
If you cannot make the client send the number then the following could help:
Make General.BRGEW as string.
Create another property e.g. General.BRGEWAsInt
public class X {
public string BRGEW {get; set;}
public int BRGEWAsInt => Int32.TryParse(BRGEW, out var number)
? number
: 0;
}
You don't need to make a property, you could just parse when you need.

In C#, how to take null input from keyboard into nullable type boolean variable?

I want to do something like this -
using System;
class MainClass
{
public static void Main ()
{
bool? input;
Console.WriteLine ("Are you Major?");
input = bool.Parse (Console.ReadLine ());
IsMajor (input);
}
public static void IsMajor (bool? Answer)
{
if (Answer == true) {
Console.WriteLine ("You are a major");
} else if (Answer == false) {
Console.WriteLine ("You are not a major");
} else {
Console.WriteLine ("No answer given");
}
}
}
Here if user gives no answer and simply presses enter, the variable input must store the value null and output must be No answer given.
In my code, input of true and false is working fine.
But if no input is given and enter is pressed the compiler throws the exception
System.FormatExeption has been thrown
String was not recognized as a valid Boolean
So how to get null value stored in variable input so that output is No answer given
Here,
the question String was not recognized as a valid boolean C#
is obviosly not a duplicate as it does not want to take null input directly from keyboard. And if such input can't be taken, what is the utility of nullable type, as there would be work around as well?
bool input;
Console.WriteLine("Are you Major?");
if (!bool.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("No answer given");
}
else
{
//....
}
Or using C# 7:
if (!bool.TryParse(Console.ReadLine(), out bool input))
{
Console.WriteLine("No answer given");
}
else
{
// Use "input" variable
}
// You can use "input" variable here too
bool? finalResult = null;
bool input = false;
Console.WriteLine("Are you Major?");
if (bool.TryParse(Console.ReadLine(), out input))
finalResult = input;
}
Using the above technique finalResult will be null if the input cannot be parsed as either true or false.
You could surround your parse with a try-catch, and on catch (so if something other than true or false is given by the user) set input to null.

Input string was not in a correct format. Expected type in Decimal type

I am not inserting any value in VOUCHER_NO column and updating it.
But it is giving me error as
Input string was not in a correct format.Couldn't store <> in VOUCHER_NO Column. Expected type is Decimal.
Below is my code
drpayinfo[0]["VOUCHER_NO"] = e.Record["VOUCHER_NO"];
Update
I am using Oracle DB and its datatype is NUMBER (10)
Seems your e.Record["VOUCHER_NO"] have some unwanted content which is not convertible to decimal. Try this way checking before assignment or conversion
if(e.Record["VOUCHER_NO"] != "")
{
drpayinfo[0]["VOUCHER_NO"] = Convert.ToDecimal(e.Record["VOUCHER_NO"]);
}
But more safer way to detect and ignore bad content is
decimal result;
if (Decimal.TryParse(e.Record["VOUCHER_NO"], out result))
{
drpayinfo[0]["VOUCHER_NO"] = result;
}
else
{
// do stuff if failed to parese
}
Based on your comments on other answers, your value is an empty string. This cannot directly be converted to a decimal. You must decide some action to take instead.
They following code will try to convert it, and take an action if not. TryParse is your friend for conversions!
decimal num = 0;
if (!Decimal.TryParse(e.Record["VOUCHER_NO"], out num))
{
//Throw some error, maybe set num to some default and assign...
//The appropriate action in this situation depends on your needs.
}
else
{
//You can safely assign the value
drpayinfo[0]["VOUCHER_NO"] = num;
}

c# try and catch/ error handling

I am currently working on a program and I am finalising it by going over with error handling. I have several cases which look like:
int stockbankInput = Convert.ToInt32(Console.ReadLine());
Here, the user must enter either 1, 2, 3. I have tried to use an if statement to catch the error if anybody inputs a blankspace/string/character or a number that is not 1,2 or 3 but it doesn't work in the same sense as a string input. Below is what I have tried:
if(stockbankInput == null)
{
Console.WriteLine("Error: Please enter either 1, 2 or 3");
stockbankInput = 0;
goto menuRestartLine;
}
However, you cannot link 'null' with an integer input, only a string. Can anybody help with this please?
Use the Int32 TryParse method:
int input;
var successful = Int32.TryParse(Console.ReadLine(), out input);
if (!successful)
// do something else
else
return input;
You're checking if an int is null, which will always return false because an int cannot be null.
You can use 'int?' (Nullable int) but Convert.ToInt32 will not return null. If the value of the int cannot be resolved it will resolve to the default value of zero. You can either check if the returned int is zero or do some further checking of the returned string:
int input = 0;
string errorMessage = "Error: Please enter either 1, 2 or 3";
while(true)
{
try
{
input = Convert.ToInt32(Console.ReadLine());
if (input == 0 || input > 3)
{
Console.WriteLine(errorMessage);
}
else
{
break;
}
}
catch(FormatException)
{
Console.WriteLine(errorMessage);
}
}
With this you your returned value "int input" will either be 0 or the number you entered and FormatExceptions caused by the string to convert containing symbols other than the digits 0-9 will be caught in the try/catch statement.
give this sample program a try:
static void Main(string[] args)
{
int stockbankInput = 0;
bool firstTry = true;
while(stockbankInput < 1 | stockbankInput > 3)
{
if(!firstTry)
Console.WriteLine("Error: Please enter either 1, 2 or 3");
firstTry = false;
Int32.TryParse(Console.ReadLine(), out stockbankInput);
}
}
First of all, don't use goto statements. They are considered bad practice, and it's like a blinding red light when reading your question - that's all I can focus on.
As per your question, an int or Int32 cannot be null. So you can't compare it to null. Give it a default value, and then check that.
This is a scenario where you don't need to check for an error, but just need to validate input. Use TryParse, which will set your out parameter if the parse is successful, or else set it to 0.
Next, you want to loop until you are given good input. An if statement is executed once, a loop will guarantee that when you leave it, your input will be valid.
Lastly, the firstTry is just a nice way to let the user know, after their first try, that they screwed up.

Error happening when no value

I created a program that requires the user to input a value into a text box. I'm trying to have the text box default to 0 if there is no value put in by the user.
Currently, if there is no value put in and the calculation is attempted I get the error "input string was not in a correct format" error.
This is what I have:
cexp = int.Parse(currentexp.Text);
currentexp.Text = "";
I want to try to do something like this:
if (currentexp.text == "")
set cexp = 0
So if the text box is empty then I want to set the variable cexp to equal 0.
Solution 1 : You can use Conditional operator for setting the default value.
int cexp=(!String.IsNullOrWhiteSpace(currentexp.Text)) ? Convert.ToInt32(currentexp.text) : 0;
Solution 2: You can use int.TryParse() to perform the validation.
int cexp;
if(int.TryParse(currentexp.Text,out cexp))
{
//conversion successfull do some thing here
}
else
{
//conversion failed so do something here
}
You can use LINQ and conditional operator:
cexp = !currentexp.Text.All(char.IsDigit) ||
!currentexp.Text.Any() ? 0 : int.Parse(currentexp.Text)
This will set cexp to zero when currentexp.Text contains one or more non-digit characters.
It might be good to use int.TryParse for this, since the user is entering in data.
int cexp = 0;
if (!int.TryParse(textBox1.Text, out cexp))
{
var result = MessageBox.Show("An invalid entry was entered, do you want to use 0 instead?",
"Invalid Entry", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
//do stuff to continue here
//cexp will already be 0
}
else
{
//don't continue, they wanted to try again
}
}
This will default the value of cexp to 0, and if the user enters something invalid it will warn them (and still keep cexp at 0). If they put in a correct value, then cexp will be updated to what the user entered.
If you don't want to warn the user or anything, and just want to continue, this will work.
int cexp = 0; //default to 0
int.TryParse(currentexptextBox1.Text, out cexp); //try to get a number, if it fails, cexp will still be 0

Categories