Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct zero length check expressions #16463

Merged
merged 4 commits into from
Jul 22, 2024
Merged

Correct zero length check expressions #16463

merged 4 commits into from
Jul 22, 2024

Conversation

MikeAlhayek
Copy link
Member

I noticed many invalid expression used in OC when checking for a zero elements in a collection.

Here is explanation

List<string> items = null;

if(items?.Count == 0)
{
	// This will evaluate false since null does not equals 0.
}

if(items == null || items.Count == 0)
{
	// This will evaluate true since items either null OR is not null and it's count is 0.
}

if(items?.Count > 0)
{
	// This check is okay because null items will return false and if the Count is 0 will also false.
}

@Piedone it would be nice to add an analyzer to guard against such a count check. Maybe related to #7950

@MikeAlhayek MikeAlhayek requested a review from Piedone July 19, 2024 21:26
Copy link
Contributor

This pull request has merge conflicts. Please resolve those before requesting a review.

@MikeAlhayek
Copy link
Member Author

@gvkries feel free to leave code review and approve PRs when you visit them

@@ -111,7 +111,7 @@ private async Task<IEnumerable<ContentTypeDefinition>> GetContainedContentTypesA
{
var settings = (await _contentDefinitionManager.GetTypeDefinitionAsync(contentType))?.Parts.SingleOrDefault(x => x.Name == partName)?.GetSettings<FlowPartSettings>();

if (settings?.ContainedContentTypes?.Length == 0)
if (settings?.ContainedContentTypes == null || settings.ContainedContentTypes.Length == 0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI I checked if the more succinct items?.Any() == false pattern would work. It wouldn't, as it (I don't understand why) produces null; and it also violates CA1860, nudging you towards items?.Count == 0. So, that's not an option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants