In memory class generation with attribute and methods - c#

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.

Related

C# Practical usage of the dynamic keyword [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How will you use the C# 4 dynamic type ?
What would be actual practical usages of the dynamic keyword?
dynamic a = 1;
a.Crash();
I know the case where it is more readable in XML chains, but, other than that, what is it good for?
Here a good article:
As a developer, you use the dynamic
keyword with variables expected to
contain objects of uncertain type such
as objects returned from a COM or DOM
API; obtained from a dynamic language
(IronRuby, for example); from
reflection; from objects built
dynamically in C# 4.0 using the new
expand capabilities.
Using the Dynamic Keyword in C# 4.0
It's particularly useful in COM interop scenarios, where you normally have to write a lot of interop plumbing code.
The most practical use i've found is dealing with COM interop scenarios. Many legacy COM components end up generating signatures that are unusable from managed code without a great deal of casting due to many items getting marshaled as object. It leads to code like the following.
IUser GetAUser() { ... }
IUser user = GetAUser();
IAddress address = (IAddress)user.GetAddress();
int zipCode = (int)address.GetZipCode();
This gets even worse with deeply nested hierarchies. While this code is type safe in the sense that it doesn't violate any CLR rules it's unsafe in the sense that the developer is depending on implementation details of the types in order to get the work done. It's really no safer than the dynamic equivalent.
dynamic GetAUser() { ... }
int zipCode = (int)GetAUser().GetAddress().GetZipCode();
The DLR(Dynamic Language Runtime) basically enables everyone to talk to everyone. That includes not just Python and Ruby, but Silverlight, Office/COM, and others.
As Chris mentioned it is very useful in COM interop scenarios.
Also, it is very useful on asp.net-mvc-3. You can have views with dynamic a model. You also have ViewBag object that can hold anything.
And another use is to hold a json object, if you implement a DynamicObject class. This is very useful when consuming APIs.
Using the dynamic keyword with POCOs can be extremely useful when you have several method overloads and you've received the the argument as an object. Cast the argument to dynamic and it will resolve the correct overload based on runtime type-- doing without dynamic ends up being a series of if/elseif statements, yuck.
Using the dynamic keyword with DynamicObjects subclasses allows you to get rid of boiler plate, write fluent api's more easily and create code that is by far more malleable. For example, here is a dynamic api that get rid of a ton of boilerplate code related to MVVM binding http://code.google.com/p/impromptu-interface/wiki/UsageMVVM

Looking for a way to manipulate .Net CIL at runtime

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.

Extending C# language?

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?

Java language features which have no equivalent in C#

Having mostly worked with C#, I tend to think in terms of C# features which aren't available in Java. After working extensively with Java over the last year, I've started to discover Java features that I wish were in C#. Below is a list of the ones that I'm aware of. Can anyone think of other Java language features which a person with a C# background may not realize exists?
The articles http://www.25hoursaday.com/CsharpVsJava.html and http://en.wikipedia.org/wiki/Comparison_of_Java_and_C_Sharp give a very extensive list of differences between Java and C#, but I wonder whether I missed anything in the (very) long articles. I can also think of one feature (covariant return type) which I didn't see mentioned in either article.
Please limit answers to language or core library features which can't be effectively implemented by your own custom code or third party libraries.
Covariant return type - a method can be overridden by a method which returns a more specific type. Useful when implementing an interface or extending a class and you want an overriding method to return a type more specific to your class. This can be simulated using explicit interface implementation in C#, but there's no simple equivalent when overriding class methods.
Enums are classes - an enum is a full class in java, rather than a wrapper around a primitive like in .Net. Java allows you to define fields and methods on an enum.
Anonymous inner classes - define an anonymous class which implements a method. Although most of the use cases for this in Java are covered by delegates in .Net, there are some cases in which you really need to pass multiple callbacks as a group. It would be nice to have the choice of using an anonymous inner class.
Checked exceptions - I can see how this is useful in the context of common designs used with Java applications, but my experience with .Net has put me in a habit of using exceptions only for unrecoverable conditions. I.E. exceptions indicate a bug in the application and are only caught for the purpose of logging. I haven't quite come around to the idea of using exceptions for normal program flow.
strictfp - Ensures strict floating point arithmetic. I'm not sure what kind of applications would find this useful.
fields in interfaces - It's possible to declare fields in interfaces. I've never used this.
static imports - Allows one to use the static methods of a class without qualifying it with the class name. I just realized today that this feature exists. It sounds like a nice convenience.
Java has packages that reflect a hierarchy and filesystem layout, while in C# the assemblies are irrespective of the namespace hierarchy.
Octal literals! :D
int x = 0245; System.out.println(x);
165 is outputted. Fun :)
Java's generics allow type wildcards. For example, <T extends Object & Comparable<? super T>> T Collections.max(Collection<? extends T>) { ... } is not expressable in C#.
In C#, you cannot have a return statement in a finally block.
I don't know if you want this in your language, but I guess Type Erasure can be seen as a feature to some.

Overriding a private method with Reflection

Is it possible to override a private method by using Reflection in .NET 3.5?
Well, it would need to be virtual to be possible to override it (by writing a dynamic type that inherits from the class), and you can't have a private virtual (it makes no sense). You could perhaps override an internal virtual, but I suspect even this may hit security issues. So ultimately, I'd say no.
Not by using Reflection alone. Perhaps the best you could do is to use Reflection, combined with Reflection.Emit or the CodeDom to duplicate the class into a new namespace. When you come across the private method you want to replace, you don't copy it, you emit your replacement.
However, there are many techniques a developer can use that make this technique much, much harder. Breaking the implementation of the class into many private or internal classes is one such.
Note: using the CodeDom you'd have to build the graph in memory, compile it, and then load the resulting assembly.
This is probably a LOT more trouble than it is worth.
The other way to do it would be to use Reflector to disassemble the class, take the code and build your own class from it with the method replace. Again there are significant technical and legal hurdles to overcome. You may learn a lot from the disassembled code though.
Not by using Reflection. You need to use some sort of AOP.
Typemock Isolator is supposed to be able to do this, but does so through the .NET profiler APIs (according to Roy Osherove in The Art of Unit Testing).

Categories

Resources