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)
Related
Just wondering if there is a way to use LINQ in C++/CLI. I found one post that was focused on VS 2008 and required a bunch of workarounds for the System::String class. I have seen some framework replacements on CodeProject, but I was wondering if there is a way to use it directly in C++/CLI. If you can, anyone have a good example?
You can use the Linq methods that are defined in the System::Linq namespace, but you'll have to jump through a couple extra hoops.
First, C++/CLI doesn't support extension methods. However, the extension methods are regular methods defined on various classes in System::Linq, so you can call them directly.
List<int>^ list = gcnew List<int>();
int i = Enumerable::FirstOrDefault(list);
Second, C++/CLI doesn't support lambda expressions. The only workaround is to declare an actual method, and pass that as a delegate.
ref class Foo
{
public:
static bool GreaterThanZero(int i) { return i > 0; }
void Bar()
{
List<int>^ list = gcnew List<int>();
int i = Enumerable::FirstOrDefault(list, gcnew Func<int, bool>(&Foo::GreaterThanZero));
}
}
Are you talking about "Language Integrated Query" or the System::Linq namespace? Every programmer I know prefers the function call syntax instead of LINQ syntax.
C++/CLI does not support LINQ syntax. Databases have supported a form of language integrated query in the past, called Embedded SQL, which is pretty much dead these days. Embedded SQL (and later LINQ-to-SQL) was a dumb idea to begin with, people have since figured out that database query logic should be in the database and not mixed into the business logic.
LINQ-to-objects is a more useful idea, but SQL syntax just feels out of place. So C# programmers tend to call the LINQ library functions directly.
C++ doesn't really need LINQ, because we have templates. The standard library algorithms made possible by templates are a superset of the advantages of LINQ: They can be specialized for particular containers, but you get a good default implementation without any help from the container class. And they compile to much more efficient code, because overload resolution happens after specialization (unlike generics). Ok, templates aren't as good for runtime reflection as generics, but C# extension methods don't play well with runtime reflection either. The biggest drawback of the C++ standard algorithms has been the verbosity of writing predicate functors, but C++0x introduces lambdas which take care of that.
Really what C++/CLI needs is a version of the standard algorithms that works on .NET containers. And here it is. For example, LINQ's Where method corresponds pretty closely to find_if. Now we just need Microsoft to hurry up and implement the final C++0x spec.
I've used decompiler to get the sources of some library in C#. One of unknown (to me) constructs it produced is the following:
Action action = null;
<>c__DisplayClass9 class2;
action = new Action(class2, (IntPtr) this.<OptimizeVisuals>b__6);
Things like <>c__DisplayClass9 or (IntPtr) this.<OptimizeVisuals>b__6 I just cannot grok.
What's more, this expression cannot be compiled with C# compiler, so I need to come up with something more friendly. Tried to google parts of this, but with no luck. Could you give me some hints? It seems it can have something to do with anonymous methods, but that's my best guess.
Thanks in advance.
EDIT: Maybe my initial question was not very clear about what I need to achieve. So just to reemphasize: I need to convert the code mentioned to the normal C# code, doing the same thing as before de-compilation. My task is to change certain things in the library I'm decompiling, while keeping other functionality (like the mentioned one) intact. This is really important thing for me, so I'd really appreciate if somebody could help me with this.
The compiler generates some members for auto-implemented properties, anonymous methods and such. To prevent collisions with your own names, the compiler uses names that are illegal in C# (but still legal in the CLR).
In C++ I would get the address of the function and overwrite the first few bytes to a jmp to my function, do some stuff, restore the original bytes, and call the original function.
Can I do something like this in C#?
The .NET Profiler API is the closest "Microsoft-approved" way of intercepting methods at runtime. As already mentioned, this is somewhat difficult to implement and I am not aware of a library that makes this easy to implement using purely managed code.
While researching options for this myself a few months ago, I stumbled on CLR Method Injection, which is an article with source code explaining how to intercept methods at runtime. I considered using this myself, and even had the sample project working, but ultimately concluded that I needed more than method interception and would need a different solution. However, this approach directly answers your question.
Lastly, what I ended up doing was developing Afterthought as an open source alternative to PostSharp, which runs as a post-compile step and allows you to modify existing methods to call other code, or replace the method implementations altogether. I am working right now on a new fluid syntax, which I will include a sample of now to provide an example to help you see how this AOP approach would meet your needs:
Methods
.Named("Sum")
.WithParams<int[]>()
.Before((T instance, ref int[] values)
=> { var s = new Stopwatch(); s.Start(); return s; })
.After((instance, stopwatch, values)
=> instance.Result = (int)stopwatch.ElapsedMilliseconds);
In this case while amending an existing type with a Sum method I am introducing code before and after the method to measure the execution time. After running Afterthought against the original compiled class, the resulting Sum method would have calls to these lambda expressions (the C# compiler just turns them into static methods) before and after the method body. I could have just as easily called Implement and replaced the entire method implementation.
I hope one of these approaches meets your needs. In my case, I went the AOP route because I wanted to do more than interception, such as implementing interfaces, adding new methods/properties, etc. I also wanted something that would not introduce dependencies at runtime or concerns about stability or performance in the runtime environment--compile-time processing is just safer and easier to test.
Do you want to hook at runtime or do you want to patch the binary?
To hook at runtime you can use the profiling api(relatively difficult):
http://msdn.microsoft.com/en-us/magazine/cc188743.aspx
To hook at compiletime you can use an IL rewriter, such as PostSharp.
The technique you're looking for is called AOP - Aspect Oriented Programming. You can find several frameworks for C# if you goggle a little.
Update: You can find plenty of links and info in this question: Built-in AOP in C# - is it on the way?
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?
After looking at how Go handles interfaces and liking it, I started thinking about how you could achieve similar duck-typing in C# like this:
var mallard = new Mallard(); // doesn't implement IDuck but has the right methods
IDuck duck = DuckTyper.Adapt<Mallard,IDuck>(mallard);
The DuckTyper.Adapt method would use System.Reflection.Emit to build an adapter on the fly. Maybe somebody has already written something like this. I guess it's not too different from what mocking frameworks already do.
However, this would throw exceptions at run-time if Mallard doesn't actually have the right IDuck methods. To get the error earlier at compile time, I'd have to write a MallardToDuckAdapter which is exactly what I'm trying to avoid.
Is there a better way?
edit: apparently the proper term for what I call "safe duck-typing" is structural typing.
How can you know if a cow walks like a duck and quacks like a duck if you don't have a living, breathing cow in front of you?
Duck-typing is a concept used at run-time. A similar concept at compile-time is structural typing which is AFAIK not supported by the CLR. (The CLR is centred around nominative typing.)
[A structural type system] contrasts with nominative systems, where comparisons are based on explicit declarations or the names of the types, and duck typing, in which only the part of the structure accessed at runtime is checked for compatibility.
The usual way to ensure that duck-typing throws no exception at run-time are unit-tests.
DuckTyping for C#
Reflection.Emit is used to emit IL that directly calls the original object
I don't think this library will give you compile time errors thought, I am not sure that would be entirely feasible. Use Unit Tests to help compensate for that.
I don't think there's another way in which you would get a compile time error.
However, this is something that Unit Testing is great for. You would write a unit test to verify that
DuckTyper.Adapt<Mallard, IDuck>(mallard);
successfully maps.
I know that implicit interfaces (which is what Go interfaces are) were planned for VB 10 (no idea about C#). Unfortunately, they were scrapped before release (I think they didn’t even make it into beta …). It would be nice to see whether they will make an appearance in a future version of .NET.
Of course, the new dynamic types can be used to achieve much the same but this is still not the same – implicit interfaces still allow strong typing, which I find important.