How to translate conditions (without brackets) correctly? - c#

I have condition, where are no ( ) brackets inside coded by programmer... How can I bracket such ugly coded correctly?
if( c_1 && c_2 || c_3 || c_4 && c_5 || c_6 && c_7 || c_8 || c_9 && c_10)

&& has higher precedence1 in C# than ||. That means your expression is effectively:
if ((c_1 && c_2) || c_3 || (c_4 && c_5) || (c_6 && c_7) || c_8 || (c_9 && c_10))
For further readability, I'd probably extract conditions into local variables with meaningful names. For example:
bool recentlyActive = (c_1 && c_2) || c_3;
bool passwordDisabled = (c_4 && c_5) || (c_6 && c_7);
bool userBanned = c_8 || (c_9 && c_10);
if (recentlyActive || passwordDisabled || userBanned)
{
...
}
1 Precedence in C# is documented in the specification, but it really comes directly out of the grammar. I'm glad of that documentation though, because I wouldn't want to have to read the grammar every time I wanted to understand how operators bind...

Related

Selenium C# displaying custom exceptions if booleans marked false?

I am coding a selenium test case to verify all elements are present on a web page and Im fairly green at coding so bear with me here. I have boolean vars set up for each element and if not found, I mark them false. At the end of my code/test, I want to display custom exceptions for each false boolean encountered. What's the easiest way to go about this?
if (!headerLogoPresent || !headerMsgDropPresent || !headerMsgDropSubGeneralPresent || !headerUserDropPresent || !headerUserDropSubProfilePresent ||
!headerUserDropSubCredentialsPresent || !headerUserDropSubSettingsPresent || !headerUserDropSubChgPassPresent || !headerUserDropSubRstGridPresent ||
!headerUserDropSubLogOffPresent || !headerSupportDropPresent || !headerSupportDropSubBasePresent || !headerSupportDropSubFaqPresent || !headerSupportDropSubTicketPresent
|| !emailTextInputFieldPresent || !saveButPresent || !bodyTextProfilePresent || !bodyTextEmailPresent || !bodyTextCopyrightPresent)
{
//then throw custom exception for each variable marked false;
}

Why .NET executes code on false IF statement?

I have following code:
var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false
&& (string == "V" || string == "N")
&& someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
>> Code
}
I have tested adding .Date or even specifiing exact year from the DateTime struct, but nothing worked.
When executing the code, even if
someDate.Value.Date > dateFrom.Date
equals 1700 > 2018, the code executed as if it was true, even though the debugger says it´s false.
When I removed this part from the condition, following code:
someDate.HasValue && object.SomeOtherDate.HasValue
When I made someDate null, so someDate.HasValue is false, the if statement still executes as true.
What did it fix? Taking these two conditions to another if:
var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false
&& (string == "V" || string == "N"))
{
if (someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
>> Code
}
else
{
>> Code
}
}
The code works, but it´s way too ugly. I'm running on Visual Studio 2017 Pro.
Any ideas why it behaves like that? Executing false statements?
Thanks
Your if statement performs different then expected, because it is parsed different as you wouls expect.
object.nullablebool.HasValue ? object.nullablebool.Value : false && ... is parsed as object.nullablebool.HasValue ? object.nullablebool.Value : (false && ...). So if object.nullablebool has a value, thats the result of the condition. To fix this you have to add parenthesis like this:
if ((object.nullablebool.HasValue ? object.nullablebool.Value : false )
&& (string == "V" || string == "N")
&& someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
// if body
}
Let's brush up your code (please, get rid of names like string, object; change them into meanful names):
// You don't want any formatting but a simple constructor
var dateFrom = new DateTime(dateProperty.Value.Year - 1, 4, 1);
// object.nullablebool == true - if object.nullablebool has value and the value is true
if (object.nullablebool == true && (string == "V" || string == "N")) {
// if someDate.Value is null the result will be false
// All we have to do is to propagate the null: ?. in someDate?.Date
if (someDate?.Date > dateFrom.Date && object.SomeOtherDate.HasValue) {
// Code
}
else {
// Code
}
}

C# Looking for similar needle in haystack (for OCR)

I've been working on an OCR program that accepts a photo with text in it (in this specific case, a driver's license) as well as a first name and a last name as arguments.
Once the software reads the id photo, I search for the first and last name in the recognized text. Unfortunately, as the image quality can be pretty low, it will sometimes not get the name quite right.
Is there a way I could look for a SIMILAR needle in a haystack? That is, look for any occurrences that are similar to the first/last name? For example:
Needle: campbell
Haystack:
operaioxsllcence
gcltdriver
exries13NOV2020
carnpbeiljtttj
...
The string that would be close enough is "carnpbeil".
This is what I'm using now, and it only helps in very specific situations:
private bool SourceContains(string haystack, string needle)
{
bool ret = false;
if (haystack.Contains(needle) ||
haystack.Replace("l", "i").Contains(needle) ||
haystack.Replace("i", "l").Contains(needle) ||
haystack.Replace("0", "o").Contains(needle) ||
haystack.Replace("o", "0").Contains(needle) ||
haystack.Replace("j", "d").Contains(needle) ||
haystack.Replace("d", "j").Contains(needle) ||
haystack.Replace("i", "j").Contains(needle) ||
haystack.Replace("j", "i").Contains(needle) ||
haystack.Replace("e", "f").Contains(needle) ||
haystack.Replace("f", "e").Contains(needle) ||
haystack.Replace("r", "p").Contains(needle) ||
haystack.Replace("p", "r").Contains(needle) ||
haystack.Replace("s", "r").Contains(needle) ||
haystack.Replace("r", "s").Contains(needle) ||
haystack.Replace("r", "n").Contains(needle) ||
haystack.Replace("n", "r").Contains(needle) ||
haystack.Replace("k", "n").Contains(needle) ||
haystack.Replace("n", "k").Contains(needle) ||
haystack.Replace("h", "n").Contains(needle) ||
haystack.Replace("n", "h").Contains(needle) ||
haystack.Replace("k", "ll").Contains(needle) ||
haystack.Replace("ll", "k").Contains(needle) ||
haystack.Replace("ci", "d").Contains(needle) ||
haystack.Replace("d", "ci").Contains(needle) ||
haystack.Replace("cl", "d").Contains(needle) ||
haystack.Replace("d", "cl").Contains(needle) ||
haystack.Replace("m", "in").Contains(needle) ||
haystack.Replace("in", "m").Contains(needle) ||
haystack.Replace("rn", "m").Contains(needle) ||
haystack.Replace("m", "rn").Contains(needle)
)
{
ret = true;
}
return ret;
}
For each word in haystack calculate the levenshtein distance to needle. The word with the shortest distance is most likely to be your needle. Have a look at this question for implementations.

How to use multiple conditional operators using C#

I want to use combination of the 2 operators: the && and the || operator using C#. I have 5 variables that I would like to make sure if these conditions are met.
varRequestedDate
varTotdayDate
varExpectedDate
Approval1
Approval2
Here is what I have for my current condition but would like to add other variables adding the OR operator:
if (varRequestedDate != (" ") && varExpectedDate < varTotdayDate)
here is the pseudocode for what I would like to see after the updated version:
(if varRequestedDate is not blank
and varExpectedDate is less than varTotdayDate
and either Approved1 OR Approved2 = Yes)
send email()
i cannot figure out how to do this.
thanks
You just have to add nested parentheses:
if (varRequestedDate != " "
&& varExpectedDate < varTotdayDate
&& (Approved1 == "Yes" || Approved2 == "Yes")
)
sendEmail();
For the sake of readability and expressiveness I would extract the boolean values into meaningfully named variables:
var isDateRequested = varRequestedDate != (" ");
var isDateWithinRange = varExpectedDate < varTotdayDate;
var isApproved = Approved1 == "Yes" || Approved2 == "Yes";
if (isDateRequested && isDateWithinRange && isApproved)
{...}
You can nest logical operators using parentheses (just like arithmetic operators). Otherwise they follow a defined precedence going left to right.
if (
varRequestedDate !=(" ") &&
varExpectedDate < varTodayDate &&
(Approved1==Yes||Approved2==yes))

If statement clarification of AND/OR

I'm sorry to ask such an easy question.. I just need some clarifications, because sometimes I mix the differences up.
Can somebody please help me by explaining the difference between the following if statements?
sending = true;
if (sending && e.AssetType == AssetType.Notecard) //#1
vs.
if ((sending) && (e.AssetType == AssetType.Notecard)) //#2
vs.
if (sending || e.AssetType == AssetType.Notecard) //#3
vs.
if ((sending) || (e.AssetType == AssetType.Notecard)) //#4
In this specific case, I need it to evaluate to something like:
"If(sending == true AND e.AssetType == AssetType.Notecard)"
In an other case I need the if statement to check one string and contents of a list like:
"If(string == "Name" OR List.Contains("string"))
The first and the second statements are the same (parenthesis are not obligatory in this case, because of C# evaluation priorities!)
if (sending && e.AssetType == AssetType.Notecard)
if ((sending) && (e.AssetType == AssetType.Notecard))
just as:
if ((sending == true) && e.AssetType == AssetType.Notecard))
if ((sending) && (e.AssetType == AssetType.Notecard))
Also the 3° and the 4° statement will give the same result, for the same reason mentioned above: http://msdn.microsoft.com/en-us/library/6a71f45d.aspx
I would use these statements:
if (sending && (e.AssetType == AssetType.Notecard))
and:
if ((string == "Name") || List.Contains("string"))
(but please take care of string comparison modes, such as upper/lower cases and cultures:
String.Compare(string, "Name", StringComparison.CurrentCultureIgnoreCase) == 0
compares strings without regard of the case and with the current culture)
There is no any difference in those codes.
if ((sending) && (e.AssetType == AssetType.Notecard)) and if (sending && e.AssetType == AssetType.Notecard) evaluates into the same thing.
if(sending == true) or if(sending) is the same thing too.
If you're asking about difference between || and &&:
|| is a LOGICAL-OR. It's enough that only one condition would be TRUE to pass if
&& is a LOGICAL-AND. All conditions must be TRUE in order to pass if
In both cases the evaluation will be done from the left to right.
Example of sequence:
if ((sending) && (e.AssetType == AssetType.Notecard)) => if sending==true AND ..rest..
For the first and second statements produce the same result and for the third and fourth statements also produce the same result.
A couple of things to clarify:
In this case, parentheses are not required and it is just extra code.
When you use Logical-AND operation, the first part is always evaluated, and the second part will only be evaluated if the first part is true.
When you use Logical-OR operation, both parts are always evaluated.
When you have more than +2 expressions, then use parentheses to clarify your intentions. e.g. if(A && B || C) is the same as if((A && B) || C) because the Operators Precedence. but if you want the logical-OR operation to be execute first, then you must use parentheses to override the precedence if(A && (B || C))
Furthermore, if(A && B == C) is the same as if(A && (B == C)) because Equality operation has higher precedence than logical-AND

Categories

Resources