7

Has anyone ever tried to generate extension methods using System.CodeDom under .NET 4.0? There doesn't seem to be any way to specify a CodeMemberMethod or CodeParameterDeclarationExpression as being an extension method/parameter.

If this isn't possible, are there any good workarounds?

Thanks

LorenVS
  • 12,597
  • 10
  • 47
  • 54

2 Answers2

7

Apparently CodeDom isn't able to generate the correct code for the first parameter of an extension method, but you can cheat it like this:

var param = new CodeParameterDeclarationExpression("this string", "s");

It will blissfully ignore the fact that "this string" is not a valid type...

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • This actually fits my needs ridiculously well. I am using extension methods for syntactic reasons, nothing more, so no members on the "this" parameter will ever be accessed, so I don't even have to worry about any type checking in System.CodeDom... Thanks for the idea – LorenVS May 15 '11 at 23:27
0

See Extension Attribute

Quote:

In Visual Basic, you should use this attribute to create an extension method. For more information, see Extension Methods (Visual Basic).

In C#, you do not need to use this attribute; you should use the this (C# Reference) modifier for the first parameter to create an extension method. The compiler automatically emits ExtensionAttribute for extension methods. For more information, see Extension Methods (C# Programming Guide).

If you are writing a compiler that supports extension methods, your compiler should emit this attribute on each extension method and on each class and assembly that contains one or more extension methods.

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • 1
    It will just apply the ExtensionAttribute to the method, which is an error in C#... the compiler says to use the `this` modifier instead – Thomas Levesque May 15 '11 at 22:20
  • Are you trying to use the compiler, or reflection emit? I may have misunderstood your question, if you are referring to some kind of in-IDE script/addin; That said, you might be consider using [Compiler As A Service](http://weblogs.asp.net/britchie/archive/2010/08/08/c-compiler-as-a-service.aspx), anyway – sehe May 15 '11 at 22:27
  • 1
    I am using System.CodeDom, which is a library included in the standard .NET framework for generating code files (or assemblies). – LorenVS May 15 '11 at 23:26