How to break if-else-if using C# - c#

How do I break if-else-if.....Why its not working? its just checking all the conditions instead of performing the tasks. following is my code. I have checked it through breakpoints its moving to all conditions why it doesn't get stop after meeting the correct condition. even it is not going into the if activity it just read all the conditions and do nothing at the end.
private void ShowHash()
{
inpic = pb_selected.Image;
Bitmap image = new Bitmap(inpic);
byte[] imgBytes = new byte[0];
imgBytes = (byte[])converter.ConvertTo(image, imgBytes.GetType());
string hash = ComputeHashCode(imgBytes);
txt_selectedText.Text = hash;
GetHash();
}
private void GetHash()
{
if (txt_sel1.Text == null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null ))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (txt_sel1.Text != null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (txt_sel2.Text != null && (txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
else if (txt_sel3.Text != null && (txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel4.Text = txt_selectedText.Text;
return;
}
else if (txt_sel4.Text != null && (txt_sel5.Text == null))
{
txt_sel5.Text = txt_selectedText.Text;
return;
}
}

I strongly suspect the problem is that the Text property is never null for any of txt_sel*. Assuming these are text boxes in a UI, it's much more likely that if there's no text in the text box, the Text property will return "" instead of null. That's the way most UI frameworks handle empty controls.
I would also suggest extracting the conditions into local variables first:
bool hasSel1 = txt_sel1.Text != "";
bool hasSel2 = txt_sel2.Text != "";
bool hasSel3 = txt_sel3.Text != "";
bool hasSel4 = txt_sel4.Text != "";
bool hasSel5 = txt_sel5.Text != "";
if (!hasSel1 && (!hasSel2 || !hasSel3 || !hasSel4 || !hasSel5)
{
...
}
And ideally, give your controls more meaningful names - a collection of variables with the same prefix but then a numeric suffix is very rarely a good idea, in terms of readability.

Reason:
If there is nothing in those textboxes, textbox.Text will return an empty string ("") not null.
Solution:
Check against "" not null:
private void GetHash()
{
if (txt_sel1.Text == "" && (txt_sel2.Text == "" || txt_sel3.Text == "" || txt_sel4.Text == "" || txt_sel5.Text == ""))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (txt_sel1.Text != "" && (txt_sel2.Text == "" || txt_sel3.Text == "" || txt_sel4.Text == "" || txt_sel5.Text == ""))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
....
....
EDIT: You don't have to do ==true for boolean variables. If statement checks it against true by default. Use ! to check against false:
if (hasValue1 && (hasValue2 || hasValue3 || hasValue4 || hasValue5))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (hasValue2 && (!hasValue1 ||hasValue3 || hasValue4 || hasValue5))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (hasValue3 && (!hasValue1 || hasValue2 || hasValue4 || hasValue5))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
....
....

I think for string better to use inbuild null and whitespace check function:
bool hasValue1 = string.IsNullOrWhiteSpace(txt_sel1.Text);
bool hasValue2= string.IsNullOrWhiteSpace(txt_sel2.Text);
bool hasValue3= string.IsNullOrWhiteSpace(txt_sel3.Text);
bool hasValue4= string.IsNullOrWhiteSpace((txt_sel4.Text);
bool hasValue5 = string.IsNullOrWhiteSpace(txt_sel5.Text);
And then define if condition on these bool. This case can handle unexpected null or white space values.

That is bacause it probably doesn't find any of those conditions true.
If it would find a true condition it would execute that if block and won't event check the others.

To add to what others have said, you should really have a final else statement in there to catch issues such as this:
else
{
throw new InvalidOperationException("My If Statement is Broken");
}

Thanks to you all! My problem is solved by changing the conditions and your suggested alteration, following is the code may be helped some beginner like me.
private void GetHash()
{
bool hasValue1 = string.IsNullOrWhiteSpace(txt_sel1.Text);
bool hasValue2 = string.IsNullOrWhiteSpace(txt_sel2.Text);
bool hasValue3 = string.IsNullOrWhiteSpace(txt_sel3.Text);
bool hasValue4 = string.IsNullOrWhiteSpace(txt_sel4.Text);
bool hasValue5 = string.IsNullOrWhiteSpace(txt_sel5.Text);
if (hasValue1 && (hasValue2 || hasValue3 || hasValue4 || hasValue5))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (hasValue2 && (!hasValue1 ||hasValue3 || hasValue4 || hasValue5 ))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (hasValue3 && (!hasValue1 || !hasValue2 || hasValue4 || hasValue5 ))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
else if (hasValue4 && (!hasValue1 || !hasValue2 || !hasValue3 || hasValue5 ))
{
txt_sel4.Text = txt_selectedText.Text;
return;
}
else if (hasValue5 && (!hasValue1 || !hasValue2 || !hasValue3 || !hasValue4 ))
{
txt_sel5.Text = txt_selectedText.Text;
return;
}
else
{
CompareHash();
}
}

Related

Any way to further reduce the number of lines of code?

I'm looking for ways to reduce the number of lines of code for this function. Any help is appreciated!
private bool CanSubmitPackage ( object obj )
{
// ---- Checks if the package contains any files to be submitted ----
if ( _selectedWorkspace.Package.Files != null )
{
if ( _selectedWorkspace.Package.Files.Count > 0 )
if ( _selectedWorkspace.Package.Platform != null || _selectedWorkspace.Package.Platform != "" )
if ( _selectedWorkspace.Package.PackagePath != null || _selectedWorkspace.Package.PackagePath != "" )
if ( _selectedWorkspace.Package.PackageSize != null || _selectedWorkspace.Package.PackageSize != "" )
if ( _selectedWorkspace.Package.SubmittedBy != null || _selectedWorkspace.Package.SubmittedBy != "" )
return true;
else
return false;
else
return false;
else
return false;
else
return false;
else
return false;
}
else
return false;
}
return ( _selectedWorkspace.Package.Files?.Count > 0
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackagePath)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackageSize)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.SubmittedBy));
You can make it shorter and readable by using && operator and string.IsNullOrEmpty method:
return ( _selectedWorkspace.Package.Files != null
&& _selectedWorkspace.Package.Files.Count > 0
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackagePath)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackageSize)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.SubmittedBy));
If you're using c#6+, then you can go further (just a little bit) and use Expression Bodied method:
private bool CanSubmitPackage () => //I'm not sure about object obj argument
( _selectedWorkspace.Package.Files != null
&& _selectedWorkspace.Package.Files.Count > 0
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackagePath)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackageSize)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.SubmittedBy));
If you are going after making your code text shorted, you can declare a short named variable and use that instead of _selectedWorkspace.Package:
var p = _selectedWorkspace.Package;
return (p.Files?.Count > 0
&& !string.IsNullOrEmpty(p.Platform)
&& !string.IsNullOrEmpty(p.PackagePath)
&& !string.IsNullOrEmpty(p.PackageSize)
&& !string.IsNullOrEmpty(p.SubmittedBy));;
This is one way to do it
Update
return ( _selectedWorkspace != null
&& _selectedWorkspace.Package != null
&& _selectedWorkspace.Package.Files != null
&& _selectedWorkspace.Package.Files.Count > 0
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackagePath)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackageSize)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.SubmittedBy));
Old Ans
return ( _selectedWorkspace.Package.Files != null
&& _selectedWorkspace.Package.Files.Count > 0
&& ( _selectedWorkspace.Package.Platform != null || _selectedWorkspace.Package.Platform != "" )
&& ( _selectedWorkspace.Package.PackagePath != null || _selectedWorkspace.Package.PackagePath != "" )
&& ( _selectedWorkspace.Package.PackageSize != null || _selectedWorkspace.Package.PackageSize != "" )
&& ( _selectedWorkspace.Package.SubmittedBy != null || _selectedWorkspace.Package.SubmittedBy != "" ));
This is another way to do it
private bool CanSubmitPackage(object obj)
{
// ---- Checks if the package contains any files to be submitted ----
if (_selectedWorkspace.Package.Files == null) return false;
if (_selectedWorkspace.Package.Files.Count <= 0) return false;
if (_selectedWorkspace.Package.Platform == null && _selectedWorkspace.Package.Platform == "") return false;
if (_selectedWorkspace.Package.PackagePath == null && _selectedWorkspace.Package.PackagePath == "") return false;
if (_selectedWorkspace.Package.PackageSize != _selectedWorkspace.Package.PackageSize != "")
return _selectedWorkspace.Package.SubmittedBy != null || _selectedWorkspace.Package.SubmittedBy != "";
return false;
}
I would prefer #xneg's answer (https://stackoverflow.com/a/53096740/10588170), however, you could also drop all 'else' Statements and replace them with a single return statement after the 'if'-block.
Make sure to use string.IsNullOrEmpty(_str) in future, or you have to use && instead of ||, otherwise you will get an Exception because you are checking if _str is empty if it is null and if it is not null, you are not checking the content of _str at all. I am pretty sure that that's not what you wanna do.
I would maybe split the conditions, for example:
public bool HasFile
{
get { return _selectedWorkspace.Package.Files != null && _selectedWorkspace.Package.Files.Count > 0; }
}
public bool HasPlatform
{
get { return !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform); }
}
// Do that for all conditions
And then you can write your final if like this:
bool result = HasFile && HasPlatform && …
If you wanted to keep it largely the same, as the return for all of your IF statements failing is false, you only need to include it once. If any of your current checks fail, it won't be able to execute "return true", so you can just have one final return statement like this:
private bool CanSubmitPackage ( object obj )
{
// ---- Checks if the package contains any files to be submitted ----
if ( _selectedWorkspace.Package.Files != null )
if ( _selectedWorkspace.Package.Files.Count > 0 )
if ( _selectedWorkspace.Package.Platform != null || _selectedWorkspace.Package.Platform != "" )
if ( _selectedWorkspace.Package.PackagePath != null || _selectedWorkspace.Package.PackagePath != "" )
if ( _selectedWorkspace.Package.PackageSize != null || _selectedWorkspace.Package.PackageSize != "" )
if ( _selectedWorkspace.Package.SubmittedBy != null || _selectedWorkspace.Package.SubmittedBy != "" )
return true;
// One of the above checks failed, that's why we're running this line
return false;
}
I also prefer #xneg, #SeM, or #Mihir Dave's approach (as they're all basically the same answer), but it does come down to what you find most comfortable / readable. I would definitely use the method String.IsNullOrEmpty() to simplify your if statements however.
Additionally, what the ? does in xneg's answer: _selectedWorkspace.Package.Files?.Count is say "If Files is not null, retrieve Files.Count, otherwise return null. Then in C# a statement like, null > 0 always returns false.

1 Button 4 Comboboxes On Win Form

I have 1 button that will execute a stored procedure based off which combobox has data in it. Are multiple if statements the best course for me to account for each combobox scenario? I currently have my code like so - which works, but is a bit slow. Is there a better way to write this syntax using C# and VS2013?
private void btn1_Click()
{
if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() == "" )
{
MessageBox.Show("You failed to make a selection.");
return;
}
if (cbo1.Text.ToString() != "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() == "" )
{
//Go route1
}
if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() 1= "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() == "" )
{
//Go route2
}
if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() != "" && cbo4.Text.ToString() == "" )
{
//Go route3
}
if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() != "" )
{
//Go route4
}
}
EDIT
#MethodMan --> is this how you would go about setting up the check?
var comboBoxes = this.Controls
.OfType<ComboBox>()
.Where(x => x.Name.StartsWith("comboBox"));
foreach(var cmbBox in comboBoxes)
{
(string.IsNullOrEmpty(cmbBox.Text)) || if (cmbBox.SelectedIndex == -1)
{
//How to find which combobox is cmbBox
}
}
my suggestion will be something like this:
private void btn1_Click()
{
int data = 0;
if(cbo1.Text.ToString() != "")
data+=1;
if(cbo2.Text.ToString() != "")
data+=2;
if(cbo3.Text.ToString() != "")
data+=4;
if(cbo4.Text.ToString() != "")
data+=8;
switch(data)
{
case 1:
//Go route1
break;
case 2:
//Go route2
break;
case 4:
//Go route3
break;
case 8:
//Go route4
break;
default:
MessageBox.Show("You failed to make a selection.");
break;
}
}
i`m not sure it will do the job you want but it is a lot faster and this way you can check wich combo the user selected and wich combo he did not

cannot implicitly convert type SananPos to Void

protected void btnSave_Click(object sender, EventArgs e)
{
if (txtMagazaNo.Text != string.Empty && txtTerminalNo.Text != string.Empty && txtKullaniciAdı.Text != string.Empty &&
txtSifre.Text != string.Empty && txtParola.Text != string.Empty && comboCompany.SelectedIndex > -1 && comboCompany.SelectedIndex > -1 && comboBank.SelectedIndex > -1 && DatePicker3.SelectedDate != null && LstTaskOfUsers.Items.Count > 0)
{
if (sanalPosList == null && txtMagazaNo.Text != string.Empty && txtTerminalNo.Text != string.Empty)
{
SanalPos SanalPosControl = SanalPos.InsertSanalPos(sanalPosList[comboCompany.SelectedIndex].Id, sanalPosList[comboBank.SelectedIndex].Id, txtMagazaNo.Text, txtTerminalNo.Text, txtKullaniciAdı.Text, txtParola.Text, txtSifre.Text, "", "", txtNot.Text, 1, DateTime.Now, "");
if (sanalPosList == null)
SanalPos.InsertSanalPos(sanalPosList[comboCompany.SelectedIndex].Id, sanalPosList[comboBank.SelectedIndex].Id, txtMagazaNo.Text, txtTerminalNo.Text, txtKullaniciAdı.Text,
txtParola.Text, txtSifre.Text, "", "", txtNot.Text, 0, DateTime.Now, "");
}
}
It's highly likely that this method:
SanalPos.InsertSanalPos();
Has a return type of void.
If you need it to return something you need to change the return type to SanalPos and return an object of the same type.

evaluation of conditions in an if statement

Suppose I have this if statement:
foreach (MyModel m in SomeList)
{
if (m.pID != SomeValue && (m.xID != 0 && SomeFunction(m.xID) == false)
{
return false;
}
}
I only want SomeFunction(m.xID) == false to evaluate if m.xID != 0 so if m.xID == 0 then don't evaluate SomeFunction
For the moment, I have this if statement broken down into 2 statements and I'm looking to see how I can combine these into just one while preserving the logic. This is the original:
foreach (MyModel m in SomeList)
{
if (m.xID != 0 && SomeFunction(m.xID) == false)
{
return false;
}
if (m.pID != SomeValue)
{
return false;
}
}
If that is all your loop is doing then I would be inclined to remove the loop entirely.
Also, instead of comparing something to false, just use the ! operator.
if (SomeList.Any(MyModel m=>m.xID != 0 && !SomeFunction(m.xID) || m.pID != SomeValue))
return false;
you are looking for this || Operator (C# Reference)
if ((m.xID != 0 && SomeFunction(m.xID) == false) || (m.pID != SomeValue))
{
return false;
}

Avoid duplication of list items

I have a ListBox that contains items, which I have chosen from a ComboBox. When I chose an item from my ComboBox, it also removes that item in my ComboBox.
I have a button on my form, that let's me duplicate the selected item in my ListBox, giving me two of the same items in the ListBox.
I also have a button on my form, that let's me remove the selected item from my ListBox. If I remove an item from the ListBox, that item goes back to the ComboBox, but if I have duplicated the item and I remove both items from the ListBox, they both show up in the ComboBox.
I don't want it to be possible to have two of the same item in the ComboBox
Here's the code I have tried to use:
private void buttonRemove_Click(object sender, EventArgs e)
{
try
{
if (ComboBox.ToString().Contains("Chicken McNuggets"))
{
found = true;
}
if (!found)
{
ComboBox.Items.Add("Chicken McNuggets");
found = false;
}
ListBox.Items.Remove(ListBox.SelectedItem);
}
catch
{
MessageBox.Show(// Message);
}
}
This is my first time asking a question in here.
edit:
private void buttonRemove_Click(object sender, EventArgs e)
{
try
{
if ((String)listBox.SelectedItem == "Big Mac" || (String)listBox.SelectedItem == "Quarter Pounder" || (String)listBox.SelectedItem == "McFeast" || (String)listBox.SelectedItem == "Cheeseburger" || (String)listBox.SelectedItem == "Hamburger" || (String)listBox.SelectedItem == "Big Tasty Bacon" || (String)listBox.SelectedItem == "McChicken" || (String)listBox.SelectedItem == "Fillet-O-Fish" || (String)listBox.SelectedItem == "Chicken Nuggets")
{
comboBox.Items.Add(listBox.SelectedItem);
listBox.Items.Remove(listBox.SelectedItem);
}
else if ((String)listBox.SelectedItem == "BBQ dip" || (String)listBox.SelectedItem == "Cheddar dip" || (String)listBox.SelectedItem == "Gulerod" || (String)listBox.SelectedItem == "Hvidløgs dip" || (String)listBox.SelectedItem == "Karry dip" || (String)listBox.SelectedItem == "Ketchup" || (String)listBox.SelectedItem == "Pommes Frites Sauce" || (String)listBox.SelectedItem == "Sennep dip" || (String)listBox.SelectedItem == "Sursød dip" || (String)listBox.SelectedItem == "Æbler")
{
comboBox2.Items.Add(listBox.SelectedItem);
listBox.Items.Remove(listBox.SelectedItem);
}
else if ((String)listBox.SelectedItem == "Gulerodskage" || (String)listBox.SelectedItem == "Kanelsnegl" || (String)listBox.SelectedItem == "McDonut chokolade" || (String)listBox.SelectedItem == "Sundae m. chokoladesauce" || (String)listBox.SelectedItem == "McDonut sukkerovertræk" || (String)listBox.SelectedItem == "McFlurry Daim" || (String)listBox.SelectedItem == "McFlurry Smarties" || (String)listBox.SelectedItem == "Sundae m. jordbærdsauce" || (String)listBox.SelectedItem == "Sundae m. karamelsauce" || (String)listBox.SelectedItem == "Triple chokolade muffin" || (String)listBox.SelectedItem == "Vaffelis")
{
comboBox3.Items.Add(listBox.SelectedItem);
listBox.Items.Remove(listBox.SelectedItem);
}
else if (listBox.SelectedItem.ToString().Contains("Stor") || listBox.SelectedItem.ToString().Contains("Mellem") || listBox.SelectedItem.ToString().Contains("Lille") || listBox.SelectedItem.ToString().Contains("9") || listBox.SelectedItem.ToString().Contains("6") || listBox.SelectedItem.ToString().Contains("4"))
{
string objectToString = listBox.SelectedItem.ToString();
string[] ord = objektToString.Split(' ');
string selectedItem = listBox.SelectedItem;
var check = comboBox.Items.Cast<string>()
.ToList()
.FirstOrDefault(c => c.Contains(selectedItem));
if (check != null)
{
comboBox.Items.Add("Chicken McNuggets");
}
else
{
listBox.Items.Remove(selectedItem);
}
if (listBox.SelectedItem.ToString().Contains("Pommes Frites"))
comboBox2.Items.Add(ord[1] + " " + ord[2]);
else if (listBox.SelectedItem.ToString().Equals("Stor Coca-Cola") || listBox.SelectedItem.ToString().Equals("Mellem Coca-Cola") || listBox.SelectedItem.ToString().Equals("Lille Coca-Cola"))
comboBox4.Items.Add(ord[1]);
else if (listBox.SelectedItem.ToString().Contains("Milkshake"))
comboBox4.Items.Add(ord[1] + " " + ord[2] + " " + ord[3]);
else
comboBox4.Items.Add(ord[1] + " " + ord[2]);
listBox.Items.Remove(listBox.SelectedItem);
}
}
catch
{
MessageBox.Show(// Message);
}
}
We need to Cast to string the items from ComboBox so we can now easily check the ListBox.SelectedItem that already from ComboBox.Items.
private void buttonRemove_Click(object sender, EventArgs e)
{
try
{
string selectedItems = listBox1.SelectedItem.ToString();
var check = comboBox1.Items.Cast<string>()
.ToList()
.FirstOrDefault(c => c.Contains(selectedItems));
if (check != null)
{
}
else
{
comboBox.Items.Add("Chicken McNuggets");
listBox1.Items.Remove(selectedItems);
}
}
catch
{
//MessageBox.Show();
}
}

Categories