Evaluate condition irrespective of first outcome - c#

I know this is probably a newbie question, however I need to get a recommendation for the design of this.
I need to evaluate the result of a set of conditions and they must be evaluated irrespective of the outcome of a preceding condition. This brings the case of using regular OR(|) or short-circuit evaluation using ||.
Below is the code that I need to make a design decision about, however the end goal is to be able to evaluate or condition regardless.
private bool checkExistingBPNInSession()
{
var exDirectors = (List<ViewModels.NewContact>)Session["NewDirectorDetails"];
var exTaxConsultant=(List<ViewModels.NewContact>)Session[Resources.Global.NewTaxConsultantDetails];
var exTaRep = (List<ViewModels.NewContact>)Session["NewTaxRepresentativeDetails"];
if (exDirectors.Count() != 0 || exTaRep.Count() != 0 || exTaxConsultant.Count() != 0)
{
var QueryCheckDir = (from x in exDirectors where x.BPN==txtBusinessPartnerIdNumber.Text select x.BPN).ToList();
var QueryCheckTaxConsultant = (from x in exTaxConsultant where x.BPN == txtBusinessPartnerIdNumber.Text select x.BPN).ToList();
var QueryCheckTaxRep = (from x in exTaRep where x.BPN == txtBusinessPartnerIdNumber.Text select x.BPN).ToList();
if (QueryCheckDir.Count() > 0 || QueryCheckTaxConsultant.Count() > 0 || QueryCheckTaxRep.Count() > 0)
{
return true;
}
else
{
return false;
}
}
return false;
}
These parts here have to be evaluated:
exDirectors.Count() != 0 || exTaRep.Count() != 0 || exTaxConsultant.Count() != 0
and this also
QueryCheckDir.Count() > 0 || QueryCheckTaxConsultant.Count() > 0 || QueryCheckTaxRep.Count() > 0
Please, I am seeking the best recommendations.
Thanks guys.

If you want an evaluation done, no matter what, you should use the
|-operator - this will evaluate every condition even if the outcome of the final expression would not change (contrary to ||-operator)
Here is a simple demo using dotnetfiddle

Related

Short circuit condition fail

I've a bit problem with a short circuit condition, what I need to do is check if an array have almost 2 indexes or a string is equal to a certain value, to recreate the problem here, suppose this:
string[] favItem = new string[] { "hello", "world", "test", "foo" };
string temp = "hello";
var itemToRemove = temp.Split(',');
foreach(var fav in favItem)
{
if(fav == "foo" || (itemToRemove.Length > 1 & fav == itemToRemove[0] || fav == itemToRemove[1]))
{
//do something
}
}
so essentially I need to compare fav with a default value, if this fail, I need to check if the itemToRemove array have almost 2 indexes, if yes I need to compare the fav value in iteration, with the two indexes of itemToRemove.
Now suppose that in itemToRemove there is only one index, I'm not able to exit from this:
(itemToRemove.Length > 1 & fav == itemToRemove[0] || fav == itemToRemove[1])
in particular with & I'm trying to exit from the condition if the indexes aren't two.
In the debug mode I can see the false value with the breakpoint, but I don't understand why the code fall to:
OutOfRangeException
with itemToRemove[1] when should be leave the condition.
What am I doing wrong?
Your code has two problems.
First, the short-circuiting boolean "and" operator is &&. & is the bitwise and operator, and does not short circuit.
Secondly, && has a higher precedence than ||, so you need to group the second || together like this (itemToRemove.Length > 1 && (fav == itemToRemove[0] || fav == itemToRemove[1])). The rule of thumb to remember precedence is that and is like multiplication 0 && 1 = 0, while or is like addition 0 || 1 = 1.
Short circuit is && not &.

How to lower IL nesting depth?

I am giving NDepend a try for 2 weeks now. I still couldn't really figure it out on how to lower ILNestingDepth. I have few methods left marked as "Methods too complex - critical". And as a fix method they suggest to seperate method into smaller methods. But I couldn't fix it that way. Let me show you a method:
First Version: ILNesting Depth of Appropriate = 7
public bool Appropriate ( CompanyQuota available, CompanyQuota used )
{
/// - larger than available or
/// - less than already used area
return !( DiskQuota > available.DiskQuota || DiskQuota < used.DiskUsage ||
UploadQuota > available.UploadQuota || UploadQuota < used.UploadUsage ||
DownloadQuota > available.DownloadQuota || DownloadQuota < used.DownloadUsage ||
PersonnelQuota > available.PersonnelQuota || PersonnelQuota < used.PersonnelUsage );
}
Second Version: ILNesting Depth of Appropriate = 7
public bool Appropriate ( CompanyQuota available, CompanyQuota used )
{
/// - larger than available or
/// - less than already used area
return AvailableFromTop(available) || AvailableFromBottom(used);
}
bool AvailableFromTop ( CompanyQuota available )
{
return !( DiskQuota > available.DiskQuota ||
UploadQuota > available.UploadQuota ||
DownloadQuota > available.DownloadQuota ||
PersonnelQuota > available.PersonnelQuota );
}
bool AvailableFromBottom ( CompanyQuota used )
{
return !( DiskQuota < used.DiskUsage ||
UploadQuota < used.UploadUsage ||
DownloadQuota < used.DownloadUsage ||
PersonnelQuota < used.PersonnelUsage );
}
How does it really work?
What should I really do?
As #Patrick from NDepend team says on the comments this was a false positive report. Hence this question does not need an answer.
For the sake of the community I am keeping this question here with the answer containing only the comment of Patrick, for the "too-lazy-to-read-comments" people.

C# if statements. if not a or b

I am trying to add a number to a list but only if the number is not 255 and not 0 id like to avoid a nested if. The code I have to do this is as follows.
if (!(r == 255 || r == 0))
{
rlist.Add(r);
listBox2.Items.Add(Math.Floor(r).ToString());
}
However I am still getting 255 and 0 added to the listbox and I can not figure out why. Can anyone point out what i am doing wrong?
Thanks in advance for any help.
As others have mentioned, r is floating point. Try this:
var rFloor = Math.Floor(r);
if (!(rFloor == 255 || rFloor == 0))
{
rlist.Add(r); // might want to use rFloor here too
listBox2.Items.Add(rFloor.ToString());
}
The only explanation I see is that r is not an int, but a double or something like that.
So imagine r = 255.3...
if (!(r == 255 || r == 0)) // is true, r is not 255 and not 0
but
listBox2.Items.Add(Math.Floor(r).ToString());
adds "255" as Math.Floor(255.3) returns 255.
Forgot to suggest a solution, TarkaDaal provides one already.

C# Validation for specific input

I'm kinda new to this thread, but in short summary i'm having trouble with a small validation issue. Basically, i'm attempting to make a simple validation program that will collect a user's input and then determine if the input is valid in terms of, input being correctly implemented, the number being positive, and the number having to be either 0, 1, 2, 3, 4 or 5.
The overall program runs, but the issue i'm facing is every form of input is deemed an error, thus displaying my error statement, even if it is a valid input like 5 for example. I feel like there is a small mistake,i have made that is causing this, So is there any suggestions?
int user_input;
int count = 0;
do
{
Console.Write("\n\nUser Input:"
if ((int.TryParse(Console.ReadLine(), out user_input) == false)||(user_input < 0 || user_input != 0 ||user_input != 1 || user_input != 2
|| user_input != 3 || user_input != 4 || user_input != 5))
{
Console.WriteLine("Error : the action entered is not a valid number.");
count = 0;
}
else
count = 1;
Your mistake is because you use OR operator.
For example user print 3. In your statements one condition return false (input != 3), but all others return true.. That's why you always go into if condition..
You can use AND operator, but I can recommend you to simplify your condition. It will be more understandable and readable:
var count = 0;
do
{
Console.Write("\n\nUser Input:");
int user_input;
if ((int.TryParse(Console.ReadLine(), out user_input) == false) || (user_input < 0 || user_input > 5))
{
Console.WriteLine("Error : the action entered is not a valid number.");
count = 0;
}
else
count = 1;
}
while (count != 1);
You already got an answer about the problem with predicate logic. But you can even more simplify with linq like:
var count = (new string[]{"1","2","3","4","5"}).Contains(Console.ReadLine()) ? 1 : 0;

C#: Choosing operator depending on boolean value (in one line)

I'm trying to get away with a slick one liner as I feel it is probably possible.
I'll put my code below and then try to explain a little more what I'm trying to achieve.
for (int p = 0; p < 2; p++)
{
foreach (string player in players[p])
{
if (PlayerSkills[player].streak_count *>* 0) //This line
PlayerSkills[player].streak_count++;
else
PlayerSkills[player].streak_count = 0;
}
}
*(p==0 ? >:<) the comparison operator is chosen depending on p.
Of course what I've written is rubbish. But basically I want to use >0 when p==0, and <0 when p>>0. Is there a nice way to achieve this?
Well, you should use what is most readable, even if it is not as consice. That said...
// Invert the count for all but the first player and check for a positive number
if (PlayerSkills[player].streak_count * (p==0 ? 1 : -1) > 0)
I don't know about slick, but the following and/or combination is one line:
if ((p == 0 && PlayerSkills[player].streak_count > 0)
|| PlayerSkills[player].streak_count < 0)
...
This will only ever do the array index once (due to the p==0 condition occurring first) and so is equivalent to the "ternary" you wrote (albeit a bit more verbose).
p > 0 ? whenGreaterThanZero : whenZeroOrLess ;
E.g.
int p = 1; bool test = p > 0 ? true : false ;
Lets test = True

Categories