Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use reflection to inspect the code in a method?

Tags:

c#

reflection

I'm playing around with the C# reflection API. I can easily load Type information of classes, methods etc. in an assembly, however, now I wonder how can I load and read the code inside a method?

like image 608
koraytaylan Avatar asked Apr 22 '10 19:04

koraytaylan


People also ask

Is it good practice to use reflection in Java?

It's very bad because it ties your UI to your method names, which should be completely unrelated. Making an seemingly innocent change later on can have unexpected disastrous consequences. Using reflection is not a bad practice. Doing this sort of thing is a bad practice.

What is Java reflection used for?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

What is reflection used for?

Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object. Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.

What is reflection where can it be used C#?

Reflection in C# is used to retrieve metadata on types at runtime. In other words, you can use reflection to inspect metadata of the types in your program dynamically -- you can retrieve information on the loaded assemblies and the types defined in them.


2 Answers

Basic Answer:

You can't with the reflection API (System.Reflection).

The reason is that the reflection api is designed to work on Metadata (Type of Classes, Name and Signature of Methods, ...) but not on the data level (which would be the IL-stream itself).

Extended Answer:

You can emit (but not read) IL with System.Reflection.Emit (e.g. ILGenerator Class).

Through MethodInfo.GetMethodBody() you can get the binary IL-stream for the implementation of a method. But thats usually completely useless by itself.

There are external libraries (like Cecil) that you can use to read/modify/add/delete code inside a method.

like image 196
Foxfire Avatar answered Sep 22 '22 14:09

Foxfire


That depends on what you mean by "read the code." There are 4 forms of the code.

Code Type Can get with Reflection
The source code, i.e. the original C# or VB.NET No
The symbolic IL code No
The JITed assembly code No
The IL bytes, i.e. the actual bytes that IL is compiled to Yes

Take a look at MethodBase.GetMethodBody() for the last one. You can get the IL bytes, the local variables, exception frames etc.

like image 37
Chris Taylor Avatar answered Sep 24 '22 14:09

Chris Taylor