Can a source generator generate methods with anonymous types as parameters?

136 views Asked by At

Is it possible for a source generator to scan an assembly for used anonymous types, and generate extension methods specifically for those typse?

For example, say you have the following code

   var anon = new { Test = 123;}
   anon.SomeExtensionMethod(); // SomeExtensionMethod does not (yet) exist

Could a source generator be used to generate SomeExtensionMethod?

I've given it a quick try. The name and type information of the anonymous type is available when source generators run. However, their name contains characters invalid in non-compiler generated code, so my attempt led to something like

public static class SourceGeneratedCode
{
  public static void SomeExtensionMethod(this global::<anonymous type: int Test> value) { }
}

Which of course won't compile. So I wonder - is there any way do to this?

I would like to generate different implementations of this method for different anonymous types; meaning, SomeExtensionMethod cannot just take in object, or be generic or such.

1

There are 1 answers

0
Jason Malinowski On BEST ANSWER

No this isn't possible, since the generator still has to produce "regular" source code, and there's no way to name an anonymous type.