Reputation:
I am fairly new to the C# language and wondered something when writing code not so long ago. When I am writing while loops, I also find asking myself do I explicitly need to check if my while condition is even needed, lets take the following code for example.
while (_myList.Count > 0)
{
// do some work
}
If previously written code (by other developers) I have seen them do something like this...
if (_list.Count > 0)
{
while (_myList.Count > 0)
{
// do some work
}
}
Which is the best practice, do I even need to do this? If so why.. can someone shine some light on this topic and let me know whats best? Thanks.
Upvotes: 0
Views: 53
Reputation: 2889
You don't have to specify the if:
if (_list.Count > 0)
While loop
What a while loop does: is taking an argument and compares whats left from the operator to the the right. And returns a boolean (true or false) as long the while gets a true it will continue the loop.
IF
What an if statment does: is taking an argument and compares whats left from the operator to the the right. And returns a boolean (true or false) as long the if gets a true it will continue and run the code in the if code block.
notice:
if (_list.Count > 0) // checking for _list
{
while (_myList.Count > 0) // checking for _myList
{
}
}
In the example you have shown the "Other developer" you check on different situations so in this case it can be usefull to check on _list.Count if you don't want to run te loop when _list.Count > 0.
Conclusion
Don't do: it when you checkking on teh same list in the if and wile.
Can do: if you only want to run the wile on an certain condition or possible exception.
Upvotes: 0
Reputation: 3417
The second code example is useless. If list count is 0 or smaller, the while wouldn't be executed.
However, you have to check, if _myList
is null, maybe like this:
if (_myList == null)
//error handling here
if _myList
really was null, then you'd have a NullReferenceException
in both your code examples.
Upvotes: 0
Reputation: 8452
No you don't need to add an if
in this case.
Before entering while
condition will be evaluated and you don't iterate if <= 0.
Caution in your sample you speak of _list
and my_list
which isn't the same object.
Upvotes: 0