5

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Adding to that, in .NET4 includes even more Linq Expression support, e.g. loops and blocks.
And I think expressions create only a new function, without a new assembly. So you're spared the overhead of loading an additional assembly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.