Simple if statement - c#

What does the if statement mean here?
Merchant merchant1 =new Merchant();
if(!merchant1.SaveMerchantDdetails(x, y, z))
{
lblError.txt = "some error info";
}
else
{
}

It means that if the SaveMerchantDdetails method called on the merchant1 instance returns false it will set an error value to an error label.

When the save action for MerchantDdetails failes the method returns false in this case an error is shown by setting the error text.

If you write the code like this, it is much clearer what is happening. To have a local variable is also better for debugging.
Merchant merchant1 =new Merchant();
bool sucess = merchant1.SaveMerchantDdetails(x, y, z);
if(sucess == false)
{
lblError.txt = "some error info";
}
So your code executes the method SaveMerchantDdetails on a object of the type Merchant. If it fails, a label (lbl would hint to that...) text is set to "some error info".

Well I am not sure what exactly SaveMerchantDetails() methods does but it might mean if merchant doesn't save x.y,z then do the following in braces...

if result of SaveMerchantDdetails not true then
lblError.txt = "some error info";

If the call to the SaveMerchantDetails method returns false -- presumably because the details couldn't be saved properly for some reason -- then set the txt property of lblError to "some error info"; otherwise execute whatever code is in the else block.

The if statement is being used to determine whether the Boolean return value of the method merchant1.SaveMerchantDdetails(); is true or false.
In this case if the method returns false then a label's text property is updated with the string shown. If the method returns true then the else block will be run instead.

The method SaveMerchantDetails gets called with the arguments x, y and z. It does what ever it does and returns a boolean to indicate success or failure.
By testing !merchant1.SaveMerchantDetails(x, y, z) the code is testing for the false or error state.

There is more to this. This simple IF statement is saying that if Merchant1 from SaveMerchantDdetails is false, then output an error message (apparently generated by another function)

If you look in the Merchant class there will be a method something like
public bool SaveMerchantDdetails(var x, var y, var z)
{
bool isSaved = false;
// Save Merchant Details and check if the save worked, store whether it did in isSave
return isSaved;
}
So the code:
if(!merchant1.SaveMerchantDdetails(x, y, z))
is simply checking if the boolean return from the SaveMerchantDdetails method is true or false. If the return is false then the error is displayed.

Related

How to convert textbox to float only if not empty?

How can I convert a textbox into a float only when the textbox has value?
I currently have this float test = (float)Convert.ToDouble(textbox.Text);
It works fine, But gives an error if the textbox is empty.
I think that better solution will be:
float test = float.NaN;
if(float.TryParse(textbox.Text, out test ))
{
// your code here
}
There are many ways to do this, but generally you test with an if. For example:
float test;
if (!string.IsNullOrWhiteSpace(textbox.text))
test = (float)Convert.ToDouble(textbox.Text);
It really is as simple as including this in an If statement.
float test;
if(textbox.Text.Length > 0) //Or (textbox.Text != "")
test = (float)Convert.ToDouble(textbox.Text);
As an additional suggestion, multiple layers of validation is always a good thing. If you have something like a submit button, you should test against required fields being empty on the UI BEFORE it gets to the point where it is converted.
A very common way is to use double.TryParse to do the conversion. This way you can handle empty and invalid values with a single statement.
bool success = double.TryParse(textbox.Text, out value);
Don't forget to check success and handle a possible failure.

Value Assigned Is Not Used

I may be overlooking something, well obviously I am. I am using an uninitialized variable of type int (carRequired). I am utilizing this variable inside an IF statement (code below). However, I get a warning stating the variable is never used yet it is. Yes, I am aware of not being good practice to embed sql, however I am told to do it this way for now.
public bool UpdateDiscrepancyReport()
{
var errorStatus = false;
int carRequired ;
carRequired = cbxCarRequired.Checked == false ? 0 : 1;
var updateQuery = "my query string ";
dbf.OpenConnection(updateQuery);
bool updateStatus = dbf.OpenConnection(updateQuery);
if (updateStatus)
{
errorStatus = true;
}
else
{
MessageBox.Show(#"Error in updating DR" + tbxDRNumber.Text+#" ",#"Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return errorStatus;
}
The variable is never used. It is assigned to, but the variable is never used after that assignment; you don't do anything after assigning the result of the ternary operation to it. In fact, the variable isn't necessary at all, and neither is errorStatus (in the original code you posted), since you never do anything in the code that will change it's value after it is initialized.
The code you've posted (prior to your edit that added several more lines) is the exact equivalent of
public bool UpdateDiscrepancyReport()
{
dbf.OpenConnection(updateQuery);
return false;
}
The compiler is telling you that the variable declaration and assignment to carRequired is meaningless, because it does not affect anything in your code. Determining whether the checkbox is checked or not only has meaning if your code does something differently based on that information, and the use of carRequired as written does nothing based on the value assigned; therefore, the assignment (and variable declaration) are useless.

How to tell if an out parameter was set already?

Is there a way to know if an out parameter was set already or not. This is the pseudocode for what I am looking for:
public virtual string blabla(long num, out bool bval)
{
if (!bval.HasValue)
{
//Do some default logic
bval = defaultValue;
}
return blabla2(num, bval);
}
You can't - you can't read the variable until it's been definitely assigned within your method. You should think of it as being like a local variable, declared but not assigned any value at the start of the method - but which you must assign a value to before you return. (It's okay not to have assigned a value to it if an exception is thrown.)
If you want a parameter which carries information as input to the method as well as propagating information out, you should use ref instead of out.
See my article on parameter passing for more information.
In addition to Jon's excellent answer, if you want the parameter to still be out, but need to see if it has been assigned a value at some place inside the method, you could use a local nullable type like follows:
public virtual string blabla(long num, out bool bval)
{
bool? bvalLocal;
... //I'm assuming there is some code here that may or
//may not assign bvalLocal?
// This whole if block may not be needed if the default
// value is the default for the type (i.e. false) as
// GetValueOrDefualt() will take care of that (see
// second to last line).
if (!bvalLocal.HasValue)
{
//Do some default logic
bvalLocal = defaultValue;
}
bval = bvalLocal.GetValueOrDefault();
return blabla2(num, bval);
}

Question about compilation error related to a use in the keyword/reserved word "out"

Hello
I'm having an error with this code:
"The out parameter 'o_BlockingSquaresArr' must be assigned to before control leaves the current method"
Now this error paints each return statement of each method apart from the last one with red..
I don't understand what is the problem regarding my specific code
Please help me,
Thanks in Advance
internal bool isLegalMove(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
bool result;
if (m_GameBoard[i_Move.RowIndex, (int)i_Move.ColIndex].Coin != null)
{
result = false;
m_MessageBuffer = "You have enterd a square which is already
occupied, please try again...";
m_ErrorFlag=true;
}
else
{
result = checkIfThereIsAtLeastOneSeqInOneDirection(i_Move,out o_BlockingSquaresArr);
}
return result;
}
internal bool checkIfThereIsAtLeastOneSeqInOneDirection(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
const int k_EightDirections = 8;
bool isSequenceFound, finalRes = false;
for (int i = 1; i <= k_EightDirections; i++)
{
isSequenceFound = checkOpponentSequenceInDirection(i_Move, (eDirections)i, out o_BlockingSquaresArr);
if (isSequenceFound)
{
finalRes = true;
}
}
return finalRes;
}
internal bool checkOpponentSequenceInDirection(Square i_Move, eDirections i_Direction, out List<Square> o_BlockingSquaresArr)
{
//I've shortened this code only relevant things
Square o_AdjacentSquare = new Square();
adjacentCoin = doSwitchAndRetrieveAdjacentCoin(i_Move, i_Direction, out o_AdjacentSquare);
// ...
if (isThereAnOpponentSequence)
{
o_BlockingSquaresArr.Add(o_AdjacentSquare);
}
return isThereAnOpponentSequence;
}
As the compiler error says, an out parameter has to be definitely assigned before any non-exceptional return of a method. I can't see any assignment to o_BlockingSquaresArr anywhere. Why are you even declaring it as an out parameter to start with?
An out parameter must be assigned a value before the method returns. In your isLegalMove method, o_BlockingSquaresArr is only assigned in the else block, so the compiler detects there are some cases where it is not initialized. You must make sure that all code paths in the method assign a value to o_BlockingSquaresArr before returning
You need to assign something to the out parameter in every execution path. In your case, you forget that in one case. Simply assign a default value of the beginning of the method so you don't run into it.
I can't tell you where as you didn't include the method name it is happening in.
In the IsLegalMove function, you need to assign a value to the o_BlockingSquaresArr variable
You need to assign something to out parameters in every (normally terminating) codepath. And you don't do that.
For example in some functions you only assign to the parameter inside the for-loop. And if the loop has 0 iterations this will never happen.

c# Object obj's value is {}. What is "{}"?

I'm using some old code that runs a sql query as a reference.
At some point, it gets to something like:
sqlDataAdapter.Fill(dataSet);
DataRow dataRow = dataSet.Tables[0].Rows[0];
Object obj = dataRow[fieldName];
The old code does:
string output;
if (!string.IsNullOrEmpty(obj.ToString())) { output = obj.ToString(); }
else { output = "Not Available"; }
I changed them to:
output = obj as string ?? "Not Available"
But sometimes, it broke. As I suspected, it was happening breaking when the entry was an int. Casting as an int in those cases solved that problem.
Then another problem arose when there was no entry for obj[fieldName] of type int. When I stepped through the debugger, I was surprised to find that obj wasn't null. In VS, mousing over revealed it had a value {}.
What the heck is {}? How do I make a boolean test of it?
(In the old code, it appears .ToString() returns "" in this case and works as expected.)
{ and } are opening and closing braces and symbolic of the start and finish of an object. Hence an empty object with no special properties is depicted in shorthand as {}. The debugger uses this notation to help you visually distinguish between an empty object, an empty string and null.
If you hover over obj[fieldName] and there is no entry for fieldName, the debugger won't care about that, it'll show the value of obj. You'll have to use the immediate window or a watch/quickwatch. The debugger will only see you hovering over obj and assume you're referring to the array itself, not the contents of the array at the specified index.
In case anyone comes across again this problem.
Solution if val object is shown {} in debug mode
// Check if its not null or empty
if (!IsNullOrEmpty(val.ToString().ToArray()))
{
// Do something with val
dt.Rows.Add(val);
}
public static bool IsNullOrEmpty<T>(T[] array)
{
return array == null || array.Length == 0;
}

Categories