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

Add analyzer to spot creation via generic new() constraint #246

Open
SteveDunn opened this issue Oct 7, 2022 · 1 comment
Open

Add analyzer to spot creation via generic new() constraint #246

SteveDunn opened this issue Oct 7, 2022 · 1 comment
Labels
enhancement New feature or request

Comments

@SteveDunn
Copy link
Owner

Describe the feature

e.g. this isn't caught at compile (but is caught at runtime)

var gt = new GenericThing<MyVo>();
var v1 = gt.GetNewItem();
var v2 = gt.GetMe<MyVo>();
Console.WriteLine(v1.Value); // bang! use of uninitalized object
Console.WriteLine(v2.Value); // bang! use of uninitalized object

[ValueObject(typeof(int))]
public partial record MyVo;

public class GenericThing<T> where T : new() {
    public X GetMe<X>() where X : new() => default!;

    public T GetNewItem() => new T();
}

Note the above has generic new() constraint at the class level and method level, so need to check for both.

We need to find invocations of methods where the target method is generic (don't need to check parameters), and the return value is the generic type, and the generic type has a new() constraint.

@SteveDunn SteveDunn added the enhancement New feature or request label Oct 7, 2022
@SteveDunn
Copy link
Owner Author

Had a quick stab at this. It won't work with a semantic compilationContext.RegisterOperationAction(AnalyzeExpression, OperationKind.ObjectCreation) - it needs to use syntax, and then get the model, and then get the generic type.

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

No branches or pull requests

1 participant