Vogen
Vogen copied to clipboard
Add analyzer to spot creation via generic new() constraint
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.
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.