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

fix incorrect FirstOrDefault usage #4580

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

SimonCropp
Copy link
Contributor

No description provided.

@@ -41,7 +41,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
return;
}

ClassDeclarationSyntax declaration = syntaxToken.Parent.AncestorsAndSelf().OfType<ClassDeclarationSyntax>().FirstOrDefault();
ClassDeclarationSyntax declaration = syntaxToken.Parent.AncestorsAndSelf().OfType<ClassDeclarationSyntax>().First();
Copy link
Member

@Youssef1313 Youssef1313 Jan 9, 2025

Choose a reason for hiding this comment

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

I think it's possible to not have an ancestor ClassDeclarationSyntax (though very very unlikely anyone will hit that case).

But here is the scenario in mind:

[TestClass]
internal record TestClass1
{
}

I think both First and FirstOrDefault are not the right thing to do. Instead, we should be looking for TypeDeclarationSyntax rather than ClassDeclarationSyntax, and in this case, First makes sense.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

if that is the case, then we would get a null ref inside the call to FixClassDeclarationAsync since is does not do a null check when accessing classDeclaration.Modifiers.

unless i am missing something?

Copy link
Member

Choose a reason for hiding this comment

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

@SimonCropp Yes, exactly what I meant. I think this is already broken if the test class is a record and will have NullReferenceException currently.

Copy link
Member

Choose a reason for hiding this comment

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

We have a simple test for class named WhenClassIsInternalAndTestClass_Diagnostic, if you duplicate it, change class to record, I expect it to fail. The fix will be to look for TypeDeclarationSyntax instead of ClassDeclarationSyntax. Let me know please if you'd like to fix this bug, and if you need any additional info.

Again, thank you for all your contributions! ❤️

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