Basically what I would like to know is if there is any way to add new 'statements' to the .net based languages?
An example of what I'm looking for would be something like introducing a public class MyClass decoratorOf ClassWithLotsOfMethods and in pre-compile time changing that to be a normal class that overrides everything by default but the methods I define.
Another example would be the .net 3.5 auto properties, or extension methods, etc
This is just for fun, not that I really want to do this, just curious if is possible
Thanks!
Seba
C# doesn't allow this. You can of course tweak the generated IL with a post-compiler (like CciSharp).
Some alternative .NET languages that allow extensions are Nemerle and Boo.
There is nothing built-in.
You could of course use a PreProcessor but that won't make you popular.
Not that I know about, but take a look at PostSharp and T4 Templates and see if that can solve your problem :)
Related: Extending the Mono C# compiler: is there any documentation or precedent?
Related
Hey this is a conceptual question and create some curiosity in my mind that is it possible to create Class(not object) dynamically or in memory? and also we can define attributes and methods for this class dynamically as well.
Is this possible in any oops language ?
Yes, it is possible in .NET.
Look at System.Reflection.Emit namespace. Using types from it you can dynamically build assemblies and types in them.
Yes you can do it using java Reflection API .
Yes, it's doable in Java; the technique is generally referred to as bytecode generation. Libraries like cglib make it more doable, albeit it's going to be pretty complicated however you do it.
Is it possible to decorate a c# class with an ast attribute or call a macro and interact with the Boo compiler?
Unfortunately, no. However the Roslyn project will give you similar functionality, not necessarily for full powered boo Syntactic Macros. But it would probably be possible to do attribute macros with some effort at least.
C# has a long way to go to catch up to Boo still!
In Java we have used the javaagent argument and ASM (http://asm.ow2.org/) utilities to modify the byte code at run/load time in memory by the classloader . (aka Add a method call to a method in a class dynamically).
Once example of this is where you remove all calls to Log4j to speed up an application (http://surguy.net/articles/removing-log-messages.xml).
I’m trying to figure out how to do this same process on runtime with C# / .Net. I have seen that you can manipulate the CIL for .Net, but I haven’t found an example of this at runtime.
System.Reflection.Emit seems to be the closest .Net equitant where you can dynamically create classes, but is there a way to add to or override existing classes using this?
I have never used Mono.Cecil for generating dynamic code (it does make your life much easy if you want to instrument assemblies though).
In .Net if you want to generate code you can use System.CodeDom and System.Reflection.Emit. One particular useful class that enables you to inject methods dynamically is DynamicMethod.
Check out the newer features in .net 4, I think most of what your looking for is in the System.Dynamic namespace.
Check out this post on DuckTyping
It's been a while since I looked at it (I'm pretty much a Java bunny) but I think the Mono project had something called Cecil which did at least some of this.
I know generics are in C# to fulfill a role similar to C++ templates but I really need a way to generate some code at compile time - in this particular situation it would be very easy to solve the problem with C++ templates.
Does anyone know of any alternatives? Perhaps a VS plug-in that preprocesses the code or something like that? It doesn't need to be very sophisticated, I just need to generate some methods at compile time.
Here's a very simplified example in C++ (note that this method would be called inside a tight loop with various conditions instead of just "Advanced" and those conditions would change only once per frame - using if's would be too slow and writing all the alternative methods by hand would be impossible to maintain). Also note that performance is very important and that's why I need this to be generated at compile time.
template <bool Advanced>
int TraceRay( Ray r )
{
do
{
if ( WalkAndTestCollision( r ) )
{
if ( Advanced )
return AdvancedShade( collision );
else
return SimpleShade( collision );
}
}
while ( InsideScene( r ) );
}
You can use T4.
EDIT: In your example, you can use a simple bool parameter.
Not really, as far as I know. You can do this type of thing at runtime, of course; a few meta-programming options, none of them trivial:
reflection (the simplest option if you don't need "fastest possible")
CSharpCodeProvider and some code-generation
the same with CodeDom
ILGenerator if you want hardcore
Generics does work as templates, if that the case.
There is a way to create code in runtime -
Check is CodeProject Example:
CodeProject
In addition to Marc's excellent suggestions, you may want to have a look at PostSharp.
I've done some Meta-Programming - style tricks using static generics that use reflection (and now I'm using dynamic code generation using System.Linq.Expressions; as well having used ILGenerator for some more insane stuff). http://www.lordzoltan.org/blog/post/Pseudo-Template-Meta-Programming-in-C-Sharp-Part-2.aspx for an example I put together (sorry about the lack of code formatting - it's a very old post!) that might be of use.
I've also used T4 (link goes to a series of tutorials by my favourite authority on T4 - Oleg Sych), as suggested by SLaks - which is a really nice way to generate code, especially if you're also comfortable with Asp.Net-style syntax. If you generate partial classes using the T4 output, then the developer can then embellish and add to the class however they see fit.
If it absolutely has to be compile-time - then I'd go for T4 (or write your own custom tool, but that's a bit heavy). If not, then a static generic could help, probably in partnership with the kind of solutions mentioned by Marc.
If you want true code generation, you could use CodeSmith http://www.codesmithtools.com which isn't free/included like T4, but has some more features, and can function as a VS.NET plug-in.
Here's an older article that uses genetic programming to generate and compile code on the fly:
http://msdn.microsoft.com/en-us/magazine/cc163934.aspx
"The Generator class is the kernel of the genetic programming application. It discovers available base class terminals and functions. It generates, compiles, and executes C# code to search for a good solution to the problem it is given. The constructor is passed a System.Type which is the root class for .NET reflection operations."
Might be overkill for your situation, but does show what C# can do. (Note this article is from the 1.0 days)
I'm wondering if it's possible to wrap a method only by adding an attribute.
Example: I want to log the execution time a method takes.
[LogTimings]
public void work()
{
..
}
This is kind of wrapping a method into another one (see this python implementation).
AOP is possible in .NET. Here's an article about it. And here's a list of AOP frameworks for .NET.
Have a look at PostSharp, an AOP framework for .NET.
In terms of logging and timing, there's also a framework called Gibraltar which integrates with PostSharp and which should make it easier to collect and use the results. I keep meaning to get round to trying it...
Using only the standard .NET framework library, you would have to create the wrap functionality by deriving from System.Runtime.Remoting.Proxies.RealProxy.
This functionality you then can apply to your class, but this class has to derive from System.MarshalByRefObject.
This is quite some restriction, that's why you might want to look at 3rd party components like PostSharp.
You can do this without having to use a different compiler if you use PostSharp.
I wrote some stuff about AOP on .Net here:
Help and Information about Aspect Oriented Programming