tomh1012
tomh1012

Reputation: 284

C# Clear List if Count = 0

I was looking through some existing code and noticed that they had this section of code

if (values.Count ==0){
    values.Clear();
}

Where values is a List<'a> according to visual studio.

As far as I understand it, this section is saying "if list is empty, then empty it". If this is the case does that not make this section of code redundant, because if the list is empty then it doesn't need to be cleared?

Am I correct in assuming this? Or is this code section actually doing something else and needs to be kept?

Upvotes: 3

Views: 930

Answers (1)

Mark Parker
Mark Parker

Reputation: 137

The Clear() method of a list removes all elements. As the count (of elements) is zero, this code is effectively redundant.

However, the code should be viewed in the context of the wider routine in which it exists, so as to perhaps understand what it 'should' do rather than what it doesn't.

Upvotes: 3

Related Questions