Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# code generation in .NET 4

Does new (>2.0) .NET framework provide any enhancements to code generation?

I used CodeDom in 2.0 and I wonder if code generation can be simpler.

like image 765
peo Avatar asked Nov 05 '22 06:11

peo


1 Answers

It depends on what you want to accomplish.

You mentioned using the CodeDom to generate code- if your looking to generate methods on the fly, then you can use LINQ expressions (i cant think of a really good tutorial off of the top of my head but just google for it).

LINQ expressions have the benefit of being easier to write (in my experience), quicker to generate (especially when you write an entire class to encapsulate a single method) and very quick to execute.

The following is a VB.Net snippet of a LINQ expression that generates a function that takes in a ASP.Net control and returns its (protected) ViewState property value:

 'generate a delegate that can access the protected control property "ViewState" 
 '(by using LINQ expressions, we can avoid the performance hit of reflection)
  Dim cntrlParam As ParameterExpression = Expression.Parameter(GetType(Control), "cntrl")
  Dim vsPropertyAcessor As MemberExpression = Expression.Property(cntrlParam, "ViewState")
  dim viewStateAccessor as Func(of Control, StateBag) = Expression.Lambda(vsPropertyAcessor, cntrlParam).Compile()

We can then invoke the generated function like so:

viewStateAccessor (myCntrl)("my_vs_key")

If your looking to do static code generation, then check out the text template feature of VS.

like image 85
WiseGuyEh Avatar answered Nov 12 '22 11:11

WiseGuyEh