C# if statement with string.Contains() not working as expected - c#

I am stuck on what I thought would be a really easy problem. I am trying to redirect a user to a different website if the UserAgent does not contain a series of strings. The part I can not figure out is that the if statement works fine if I use the code below. I am happy with the results with this but something tells me that it is not good practice to only have an else statement and perform nothing if the statement proves to be true.
string strUserAgent = Request.UserAgent.ToString().ToLower();
if (strUserAgent != null)
{
if (Request.Browser.IsMobileDevice == true ||
strUserAgent.Contains("iphone") ||
strUserAgent.Contains("blackberry") ||
strUserAgent.Contains("mobile") ||
strUserAgent.Contains("windows ce") ||
strUserAgent.Contains("opera mini") ||
strUserAgent.Contains("palm") ||
strUserAgent.Contains("android"))
{
// Is this normal practice to only have an else block?
}else
{
Response.Redirect(AppState["redirectBack"].ToString());
}
When I try the next block of code the script redirects the user no matter what the UserAgent string contains. Can someone explain why this might be happening?
string strUserAgent = Request.UserAgent.ToString().ToLower();
if (strUserAgent != null)
{
if (Request.Browser.IsMobileDevice != true ||
!strUserAgent.Contains("iphone") ||
!strUserAgent.Contains("blackberry") ||
!strUserAgent.Contains("mobile") ||
!strUserAgent.Contains("windows ce") ||
!strUserAgent.Contains("opera mini") ||
!strUserAgent.Contains("palm") ||
!strUserAgent.Contains("android"))
{
Response.Redirect(AppState["redirectBack"].ToString());
}

You need De Morgan's Law. When you inverted your condition, your ORs need to become ANDs

Invert your statement using ! ("not"):
if(!(conditions)) { }
This will avoid the need to use an empty code block and you can just drop the else.
Your second codeblock will redirect when you're not on a mobile device or when your useragent contains any of the following strings. It depends on your input and your environment.
Do note that it's a lot easier to create a collection of the possibilities and check if your useragent is in there:
if(new[] {"iphone", "somephone", "otherphone" }.Any(x => useragent.Contains(x))) {}

It will always be true that at least one of your conditions will not be true. For instance, if strUserAgent.Contains(iphone) will be false if strUserAgent.Contains("blackberry") is true.
You need to change your OR (||) operator to a logical AND (&&) operator.
if (strUserAgent != null)
{
if (Request.Browser.IsMobileDevice != true &&
!strUserAgent.Contains("iphone") &&
!strUserAgent.Contains("blackberry") &&
!strUserAgent.Contains("mobile") &&
!strUserAgent.Contains("windows ce") &&
!strUserAgent.Contains("opera mini") &&
!strUserAgent.Contains("palm") &&
!strUserAgent.Contains("android"))
{
Response.Redirect(AppState["redirectBack"].ToString());
}

Not an answer, just a suggestion. You can make your code cleaner with an extension method:
public static bool ContainsAnyOf(this string source, params string[] strings)
{
return strings.Any(x => source.Contains(x));
}
And now write
if (strUserAgent.ContainsAnyOf("iphone", "blackberry", "mobile", "windows ce", "opera mini", "palm", "android"))
{
//
}

You need to reverse the entire thing. Putting !A || !B is not the same as !(A||B). In the first one if its A then it's Not B so it's True. In the second one it's False.
if (!(Request.Browser.IsMobileDevice == true ||
strUserAgent.Contains("iphone") ||
strUserAgent.Contains("blackberry") ||
strUserAgent.Contains("mobile") ||
strUserAgent.Contains("windows ce") ||
strUserAgent.Contains("opera mini") ||
strUserAgent.Contains("palm") ||
strUserAgent.Contains("android")
) )
{
Response.Redirect(AppState["redirectBack"].ToString());
}

string strUserAgent = Request.UserAgent.ToString().ToLower();
if (strUserAgent != null)
{
if (!(Request.Browser.IsMobileDevice == true ||
strUserAgent.Contains("iphone") ||
strUserAgent.Contains("blackberry") ||
strUserAgent.Contains("mobile") ||
strUserAgent.Contains("windows ce") ||
strUserAgent.Contains("opera mini") ||
strUserAgent.Contains("palm") ||
strUserAgent.Contains("android")))
{
Response.Redirect(AppState["redirectBack"].ToString());
}

Related

Simplify conditional if statement c#

I have an if statement that becoming a bit cumbersome. I want to know if there's a better way of going about multiple similar if statements such as combining into one or using a different conditional statement such as a while or do loop. Any suggestions are appreciated.
if (options.OpenCloseOverridesOptions != null && !options.OpenCloseOverridesOptions.AreEqual(OpenCloseOverridesOptions))
return false;
if (options.DeliveryOpenCloseOverridesOptions != null && !options.DeliveryOpenCloseOverridesOptions.AreEqual(DeliveryOpenCloseOverridesOptions))
return false;
if (options.PickupOpenCloseOverridesOptions != null && !options.PickupOpenCloseOverridesOptions.AreEqual(PickupOpenCloseOverridesOptions))
return false;
if (options.PickupServiceWindowOverridesOptions != null && !options.PickupServiceWindowOverridesOptions.AreEqual(PickupServiceWindowOverridesOptions))
return false;
if (options.DeliveryServiceWindowOverridesOptions != null && !options.DeliveryServiceWindowOverridesOptions.AreEqual(DeliveryServiceWindowOverridesOptions))
return false;
if (options.ServiceWindowOverridesOptions != null && !options.ServiceWindowOverridesOptions.AreEqual(ServiceWindowOverridesOptions))
return false;
if (options.LineItemsOptions != null && !options.LineItemsOptions.AreEqual(LineItemsOptions))
return false;
the rundown is I am basically checking if an object is null, if not use an extension method to determine if a similar object is equal. (I'm not overriding isEquals and getHashCode ). if the object is null I cannot call the areEquals extension method so that check is necessary.
If you want to return bool you can return the condition directly.
We can use another skill (De Morgan's laws) let! into the statement, that will reverse all logic, let the code more clear.
return
(options.OpenCloseOverridesOptions == null || options.OpenCloseOverridesOptions.AreEqual(OpenCloseOverridesOptions)) &&
(options.DeliveryOpenCloseOverridesOptions == null || options.DeliveryOpenCloseOverridesOptions.AreEqual(DeliveryOpenCloseOverridesOptions)) &&
(options.PickupOpenCloseOverridesOptions == null || options.PickupOpenCloseOverridesOptions.AreEqual(PickupOpenCloseOverridesOptions))&&
(options.PickupServiceWindowOverridesOptions == null || options.PickupServiceWindowOverridesOptions.AreEqual(PickupServiceWindowOverridesOptions) &&
(options.DeliveryServiceWindowOverridesOptions == null || options.DeliveryServiceWindowOverridesOptions.AreEqual(DeliveryServiceWindowOverridesOptions)&&
(options.ServiceWindowOverridesOptions == null || options.ServiceWindowOverridesOptions.AreEqual(ServiceWindowOverridesOptions)&&
(options.LineItemsOptions == null || options.LineItemsOptions.AreEqual(LineItemsOptions)
Try this:
if (options.OpenCloseOverridesOptions != null && !options.OpenCloseOverridesOptions?.AreEqual(OpenCloseOverridesOptions)
|| !options.DeliveryOpenCloseOverridesOptions?.AreEqual(DeliveryOpenCloseOverridesOptions)
|| !options.PickupOpenCloseOverridesOptions?.AreEqual(PickupOpenCloseOverridesOptions))
return false;
Use the safe-navigation operator that was introduced in C#6 and a single if statement with several conditions, e.g.:
if (options.OpenCloseOverridesOptions?.AreEqual(OpenCloseOverridesOptions) != true
|| options.DeliveryOpenCloseOverridesOptions?.AreEqual(DeliveryOpenCloseOverridesOptions) != true
|| options.PickupOpenCloseOverridesOptions?.AreEqual(PickupOpenCloseOverridesOptions) != true)
return false;

if else operator is not running when it should

Please check the code below. On first if section however all my conditions get false it's not going to else. Its always running the if inside codes.
To be more specific ViewBag.gtQuickDate this viewbag does not contain any value as shown below also other viewbags does not contain the value, then why it's not running the else if? Any mistake you found on operator then let me know.
if (ViewBag.subcattxt != "" & ViewBag.callFrom == "result" &
ViewBag.gtQuickDate != "2015y" || ViewBag.gtQuickDate != "2016y" ||
ViewBag.gtQuickDate != "2017y" || ViewBag.gtQuickDate != "blank")
{
}
else if (ViewBag.subcattxt != "" & ViewBag.callFrom == "result" &
ViewBag.gtQuickDate == "2015y" || ViewBag.gtQuickDate == "2016y" ||
ViewBag.gtQuickDate == "2017y" || ViewBag.gtQuickDate != "blank")
{
}
The reason for the condition evaluating incorrectly is that || has lower precedence than &, so any match of gtQuickDate renders the entire condition true.
It is generally a very bad idea to embed the current year into code, because it stops working as expected after a set period of time, requiring a recompile.
If you are looking for gtQuickDate from the last three years, you can do it like this:
int yearNow = DateTime.Now.Date.Year;
var blankOrLastThreeYears = new[] {
"blank"
, $"{yearNow - 0}y"
, $"{yearNow - 1}y"
, $"{yearNow - 2}y"
};
Now your condition can be rewritten as
if (ViewBag.subcattxt != ""
&& ViewBag.callFrom == "result"
&& blankOrLastThreeYears.Contains(ViewBag.gtQuickDate)) {
...
}
The list in blankOrLastThreeYears will contain entries for the last three years, and will update automatically for 2018, 2019, and so on.
I'm not certain what you're checking,if possible, could you separate ORs from ANDs, but please try:
if ((!(ViewBag.subcattxt.Equals(null)) && (!(ViewBag.callFrom.Equals("result"))) && (!(ViewBag.gtQuickDate.Equals("2015y"))))
{
//some other code
}
else if((!(ViewBag.gtQuickDate.Equals("2016y")) || (!(ViewBag.gtQuickDate.Equals("2017y")) || (!(ViewBag.gtQuickDate.Equals("blank"))))
{
//some other code
}
else if (ViewBag.subcattxt.Equals(null) && ViewBag.callFrom.Equals("result") && ViewBag.gtQuickDate.Equals("2015y"))
{
//some other code
}
else if(ViewBag.gtQuickDate.Equals("2016y") || ViewBag.gtQuickDate.Equals("2017y") || ViewBag.gtQuickDate.Equals("blank"))
{
//other code
}
Hope this helps.

Null value in linq where clause

I'm having an issue where I want to return results where something matches and I get an error if one of the properties I'm trying to match is null.
if (!string.IsNullOrEmpty(searchString))
{
Infos = Infos.Where(
x =>
x.FirstName.ToLower().Contains(searchString) ||
x.LastName.ToLower().Contains(searchString) ||
x.ContractNum.ToLower().Contains(searchString) ||
x.VIN.ToLower().Contains(searchString) ||
x.Claim.InitiatedBy.ToLower().Contains(searchString)
).ToList();
}
If ContractNum or VIN, for example, are null then it throws an error. I'm not sure how to check if one of these are null inside of a linq query.
You can add explicit null checks:
Infos = Infos.Where(
x =>
(x.FirstName != null && x.FirstName.ToLower().Contains(searchString)) ||
(x.LastName != null && x.LastName.ToLower().Contains(searchString)) ||
(x.ContractNum != null && x.ContractNum.ToLower().Contains(searchString)) ||
(x.VIN != null && x.VIN.ToLower().Contains(searchString)) ||
(x.Claim != null && x.Claim.InitiatedBy != null && x.Claim.InitiatedBy.ToLower().Contains(searchString))
).ToList();
You have multiple options, first is to do an explicit check against null and the other option is to use Null propagation operator.
x.FirstName != null && x.FirstName.ToLower().Contains(searchString)
or
x.FirstName?.ToLower()?.Contains(searchString) == true
But I would suggest you to use IndexOf instead of Contains for case
insensitive comparison.
something like:
x.FirstName?.IndexOf(searchString, StringComparison.CurrentCultureIgnoreCase) >= 0)
Checking the property is null or empty before comparing it it's the only way I know
if (!string.IsNullOrEmpty(searchString))
{
Infos = Infos.Where(
x =>
(!String.IsNullOrEmpty(x.FirstName) && x.FirstName.ToLowerInvariant().Contains(searchString)) ||
(!String.IsNullOrEmpty(x.LastName) && x.LastName.ToLowerInvariant().Contains(searchString)) ||
(!String.IsNullOrEmpty(x.ContractNum) && x.ContractNum.ToLowerInvariant().Contains(searchString)) ||
(!String.IsNullOrEmpty(x.VIN) && x.VIN.ToLowerInvariant().Contains(searchString)) ||
(x.Claim != null && !String.IsNullOrEmpty(x.Claim.InitiatedBy) && x.Claim.InitiatedBy.ToLowerInvariant().Contains(searchString))
).ToList();
}
EXTRA: I added a check on the Claim property to make sure it's not null when looking at InitiatedBy
EXTRA 2: Using the build in function IsNullOrEmpty to compare string to "" and nullso the code is clearer.
Extra 3: Used of ToLowerInvariant (https://msdn.microsoft.com/en-us/library/system.string.tolowerinvariant(v=vs.110).aspx) so the lowering action will act the same no matter of the culture.
You could use ?? to replace it with a acceptable value.
(x.ContractNum??"").ToLower()
I would use the null conditional operator ?, this will however, return a nullable bool? so you will need to handle that appropriately.
Some examples on how to do this:
x?.FirstName?.ToLower().Contains(searchString) == true;
x?.FirstName?.ToLower().Contains(searchString) ?? false;
An alternative method to keep the comparison logic in one place to use a sub collection of the properties and check on those:
Infos = Infos.Where(i=>
new[] {i.FirstName,i.LastName,i.ContractNum /*etc*/}
.Any(w=> w?.ToLower().Contains(searchString) ?? false))
.ToList();
(It does read out all properties, but that shouldn't cost much performance and gains much maintainability )

Nully the null error

Is there a way to tell the program that i don't care if a class reference is null.
For example:
if (playermove[i].name == "punch" || ispunchactivated == true)
{
Do the punch;
}
Why is he searching for the playermove (that can be null) and give me a null exeption error? i really don't care if the ispunchactivated is true.
Thanks.
If you put your two conditions the other way around:
ispunchactivated /*== true*/ || playermove[i].name == "punch"
// this isn't necessary
then, if the first one is true, the second one won't be checked.
However, unless you know playermove[i] won't be null if ispunchactivated is false, you should really be making the null check too, otherwise you'll still get exceptions:
ispunchactivated ||
(playermove[i] != null && playermove[i].name == "punch")
You just check it for null first.
There are not shortcuts here.
if (playermove == null || playermove[i].name == "punch" || ispunchactivated == true)
{
Do the punch;
}
Try this,
if ((ispunchactivated == true) || (playermove[i] != null && playermove[i].name == "punch" ))
{
Do the punch;
}
You can modify the if condition as follows:
if (ispunchactivated == true || (playermove!=null && playermove[i].name == "punch" ))
Just interchange the conditions and shortcircuitting will do that for you:
if (ispunchactivated == true || playermove[i].name == "punch")
{
Do the punch;
}
playermove[i] is only evaluated if ispunchactivated is false. That being said, you can still run into a null pointer exception if ispunchactivated is false and playermove[i] is null.
Change your condition as follows:
if(playermove !=null && playermove[i] != null)
{
if (playermove[i].name == "punch" || ispunchactivated == true)
{
Do the punch;
}
}

Nested 'if'-'else' statements

I have code that's very messy with the if - else if checks it is doing. The amount of branching and nested branching is quite big (over 20 if - else if and nested too). It's making my code harder to read and will probably be a performance hog. My application checks for a lot of conditions it gets from the user and so the application must check all the time for different situations, for example:
If the textbox text is not 0, continue with the next...
if ((StartInt != 0) && (EndInt != 0))
{
And then here it checks to see whether the user have choosen dates:
if ((datePickerStart.SelectedDate == null) || (datePickerEnd.SelectedDate == null))
{
MessageBox.Show("Please Choose Dates");
}
Here, if the datepickers aren't null it continues with code...
else if ((datePickerStart.SelectedDate != null) && (datePickerEnd.SelectedDate != null))
{
// CONDITIONS FOR SAME STARTING DAY AND ENDING DAY.
if (datePickerStart.SelectedDate == datePickerEnd.SelectedDate)
{
if (index1 == index2)
{
if (StartInt == EndInt)
{
if (radioButton1.IsChecked == true)
{
printTime3();
}
else
{
printTime();
}
}
This is just a small part of the checks being made. Some of them are functionals and some are for input validation stuff.
Is there any way to make it more readable and less of a performance hog?
It's not that of a performance hog. A great blog post on how to fix those common problems is Flattening Arrow Code.
I see here some mix in validation. Try to move one fields from others, and validate them separately, something like this:
if (StartInt == 0 || EndInt == 0)
{
MessageBox.Show("Please Choose Ints");
return;
}
if (datePickerStart.SelectedDate == null || datePickerEnd.SelectedDate == null)
{
MessageBox.Show("Please Choose Dates");
return;
}
In this approach you'll always say to the user what he did wrong, and your code is much simpler.
More information from Jeff's blog
One way is to refactor by encapsulating complex conditions in the following way:
public bool DateRangeSpecified
{
get
{
return (datePickerStart.SelectedDate != null)
&&
(datePickerEnd.SelectedDate != null)
&& StartInt != 0 && EndInt != 0;
}
}
and then using these "condition facade" properties
Some slight refactoring makes it easier to read to my eyes. I removed extraneous brackets and consolidated multiple IF statements that are really just AND logic.
if (StartInt == 0 || EndInt == 0)
return;
if (datePickerStart.SelectedDate == null || datePickerEnd.SelectedDate == null)
{
MessageBox.Show("Please Choose Dates");
return;
}
if (datePickerStart.SelectedDate != null
&& datePickerEnd.SelectedDate != null
&& datePickerStart.SelectedDate == datePickerEnd.SelectedDate
&& index1 == index2
&& StartInt == EndInt)
{
if (radioButton1.IsChecked == true)
printTime3();
else
printTime();
}
You can define your own predicates or generic functions with meaningful names and encapsulate you logic into those.
Here is a code example for some predicates:
public Predicate<DateTime> CheckIfThisYear = a => a.Year == DateTime.Now.Year;
public Func<DateTime, int, bool> CheckIfWithinLastNDays = (a, b) => (DateTime.Now - a).Days < b;
Now you can easily write in your code
if (CheckIfThisYear(offer) && CheckIfWithinLastNDays(paymentdate,30)) ProcessOrder();
Consider using generic delegates, like Func<> and Delegate<> for writing small blocks of your conditions using lambda-expressions -- it will both save the space and makes your code much more human-readable.
Use the return statement to stop the execution of a block.
For instance,
void Test()
{
if (StartInt==0 || EndInt==0)
{
return;
}
if (datePickerStart.SelectedDate == null || datePickerEnd.SelectedDate == null)
{
MessageBox.Show("Please Choose Dates");
return;
}
}

Categories

Resources