I am currently struggling with about 5 nested if-statements and its becoming quite confusing to look over all of them.
So, I thought about adding ternary operators instead of ifs for simple checks, see
foreach (String control in controls)
{
if (!control.Equals(String.Empty))
{
// Do some stuff
foreach (Int32 someStuff in moreStuff)
{
if (!someStuff.Equals(0))
{
// More stuff with more if equals
}
}
}
Thats how it looks like right now. Thats my idea on how to make it look a little bit more nice:
foreach (String control in controls)
{
(control.Equals(String.Empty)) ? continue : null;
// Do some stuff
foreach (Int32 someStuff in moreStuff)
{
(someStuff.Equals(0)) ? continue : null;
// More stuff
}
}
So, the questions are: 1. is is bad programming to solve it like this and 2. will it work the way I want?
No it won't, the ternary operator has to have values on the left and right of :.
Presuming you're using .NET 3.5 and above, you could do this though:
foreach( string control in controls.Where(c => !c.Equals(string.Empty)) )
{
foreach( int someStuff in moreStuff.Where(s => !s.Equals(0)) )
{
}
}
What about spliting the inner code into separate functions?
foreach (String control in controls)
{
if (!control.Equals(String.Empty))
{
foo(control);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With