C# version of __FUNCTION__ macro - c#

Does anyone has a good solution for a C# version of the C++ __FUNCTION__ macro? The compiler does not seem to like it.

Try using this instead.
System.Reflection.MethodBase.GetCurrentMethod().Name
C# doesn't have __LINE__ or __FUNCTION__ macros like C++ but there are equivalents

What I currently use is a function like this:
using System.Diagnostics;
public string __Function() {
StackTrace stackTrace = new StackTrace();
return stackTrace.GetFrame(1).GetMethod().Name;
}
When I need __FUNCTION__, I just call the __Function() instead. For example:
Debug.Assert(false, __Function() + ": Unhandled option");
Of course this solution uses reflection too, but it is the best option I can find. Since I only use it for Debugging (not Tracing in release builds) the performance hit is not important.
I guess what I should do is create debug functions and tag them with
[ Conditional("Debug") ]
instead, but I haven't got around to that.
Thanks to Jeff Mastry for his solution to this.

Unfortunately there is no equivalent version of that macro in C#. I don't consider the GetCurrentMethodName() solution equivalent to the C++ __FUNCTION__ macro. Namely becase the C++ version is a compile time computation of the name. For C# this is a runtime calculation and incurs a performance hit.
I'm not making any assumtions about the severity of the cost but there is one

The following should work, although it will be evaluated at runtime instead of during compilation.
System.Reflection.MethodBase.GetCurrentMethod().Name

I use this:
public static string CallerName([CallerMemberName] string callerName = "")
{
return callerName;
}
Usage example:
s_log.DebugFormat("{0}", CallerName());
The down side of using it is that every time you want to print the caller name, you need to jump to the function ==> time consuming & performance hit!
So, I use it for debugging perpose and if I need to print also in production code, I usually inline the function name into the log.Debug, e.g. :
s_log.Debug("CallerName");
HTH..

This is added in .NET 4.5.
See #roken's answer here:
Do __LINE__ __FILE__ equivalents exist in C#?

Related

Retrieve class implementation using Reflection [duplicate]

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?
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.
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.
You sort of can. The relevant function is MethodBase.GetMethodBody.
It's not exactly the most useful API. You can get some basic information about what's inside the method, and you can obtain the IL as a byte array. That's about it.
There's a slightly better API in the Mono.Cecil library, which exposes a MethodDefinition class with its own MethodBody implementation which contains actual Instructions, so you don't have to interpret the raw byte code. Still, if you're looking to get C# code out of it à la Reflector, you're going to be sorely disappointed. Also, Cecil isn't very well documented.
If you still want to try, then good luck.
If you don't need to do this real-time, have a look at Reflector. You can disassemble any .NET assembly (including the MS core DLLs) and see the code in your language of choice. This can be very educational.
Update Has anyone tried using Reflector on Reflector to figure out how this is done?
I'd like to provide an example of how one could explore the code inside a method. As others have explained, this can't be done easily using the native .NET Reflection API. However, using the Mono.Reflection API, you can disassemble the code programmatically using the GetInstructions() method and inspect it at runtime.
For example, the following code inspects a method and computes the number of calls inside it. As a use case for such a code, say I am a teacher (which I am) and instruct my fellow students to program a given method without using any other method, then using this code in unit tests I can verify that the given constrain is respected.
public static class MethodInfoUtil
{
public static int NbOfInnerCalls(this MethodInfo mi)
{
return mi.GetInstructions().Count(
instruction => instruction.OpCode.FlowControl == FlowControl.Call);
}
}
Example Console program:
class Program
{
static int Add(int a, int b) => a + b;
static int Doubling(int a) => Add(a, a);
static int Quadrupling(int a) => Add(Add(a, a), Add(a, a));
static void Main(string[] args)
{
Console.WriteLine("Inner method calls");
Console.WriteLine(" Add: {0}", ((Func<int, int, int>)Add).Method.NbOfInnerCalls());
Console.WriteLine(" Doubling: {0}", ((Func<int, int>)Doubling).Method.NbOfInnerCalls());
Console.WriteLine("Quadrupling: {0}", ((Func<int, int>)Quadrupling).Method.NbOfInnerCalls());
}
}
// Output:
// Inner method calls
// Add: 0
// Doubling: 1
// Quadrupling: 3
No
This is a feature slated for the next version of C#. You can use the CodeDom to get more info than reflection, but you cannot interrogate the parse tree yet.
Well there is always mono, in mono the compiler is a service, and you could get the parse trees at runtime.
The better question is why you want to?
Yes, there must be a way to achieve this: The .NET Reflector tool does this, too. Can't tell you how it's done there, though.

how to read method body and identify expressions in c# reflection? [duplicate]

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?
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.
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.
You sort of can. The relevant function is MethodBase.GetMethodBody.
It's not exactly the most useful API. You can get some basic information about what's inside the method, and you can obtain the IL as a byte array. That's about it.
There's a slightly better API in the Mono.Cecil library, which exposes a MethodDefinition class with its own MethodBody implementation which contains actual Instructions, so you don't have to interpret the raw byte code. Still, if you're looking to get C# code out of it à la Reflector, you're going to be sorely disappointed. Also, Cecil isn't very well documented.
If you still want to try, then good luck.
If you don't need to do this real-time, have a look at Reflector. You can disassemble any .NET assembly (including the MS core DLLs) and see the code in your language of choice. This can be very educational.
Update Has anyone tried using Reflector on Reflector to figure out how this is done?
I'd like to provide an example of how one could explore the code inside a method. As others have explained, this can't be done easily using the native .NET Reflection API. However, using the Mono.Reflection API, you can disassemble the code programmatically using the GetInstructions() method and inspect it at runtime.
For example, the following code inspects a method and computes the number of calls inside it. As a use case for such a code, say I am a teacher (which I am) and instruct my fellow students to program a given method without using any other method, then using this code in unit tests I can verify that the given constrain is respected.
public static class MethodInfoUtil
{
public static int NbOfInnerCalls(this MethodInfo mi)
{
return mi.GetInstructions().Count(
instruction => instruction.OpCode.FlowControl == FlowControl.Call);
}
}
Example Console program:
class Program
{
static int Add(int a, int b) => a + b;
static int Doubling(int a) => Add(a, a);
static int Quadrupling(int a) => Add(Add(a, a), Add(a, a));
static void Main(string[] args)
{
Console.WriteLine("Inner method calls");
Console.WriteLine(" Add: {0}", ((Func<int, int, int>)Add).Method.NbOfInnerCalls());
Console.WriteLine(" Doubling: {0}", ((Func<int, int>)Doubling).Method.NbOfInnerCalls());
Console.WriteLine("Quadrupling: {0}", ((Func<int, int>)Quadrupling).Method.NbOfInnerCalls());
}
}
// Output:
// Inner method calls
// Add: 0
// Doubling: 1
// Quadrupling: 3
No
This is a feature slated for the next version of C#. You can use the CodeDom to get more info than reflection, but you cannot interrogate the parse tree yet.
Well there is always mono, in mono the compiler is a service, and you could get the parse trees at runtime.
The better question is why you want to?
Yes, there must be a way to achieve this: The .NET Reflector tool does this, too. Can't tell you how it's done there, though.

Specifying locale for string interpolation in C#6 (Roslyn CTP6)

String interpolation in C#6 lets me write:
decimal m = 42.0m;
string x = $"The value is {m}";
However, a very common use case for string formatting is to specify the locale used for formatting the values. Let's say I need to use InvariantCulture for the formatting operation above, what is the syntax for that ?
This discussion suggests that I should be able to do this:
string x = INV($"The value is {m}");
Where INV is defined as
public static string INV(IFormattable formattable)
{
return formattable.ToString(null, System.Globalization.CultureInfo.InvariantCulture);
}
However, this does not work. It compiles, but it leaves my program hanging at in cmd.exe at startup - as if klr.exe, that I assume is being invoked, hangs (Compiler bug?)
This is an ASP.NET 5 Console Project in VS15 CTP 6.
What you have should work. It's the correct syntax. There's also a convenient method on the "System.FormattableString" abstract class which has the same effect as the suggested "INV" helper method.
using static System.FormattableString;
...
string x = Invariant($"The value is {m}");
I finally figured this out. As it turns out, the compiler feature relies on two types, System.FormattableString, and System.Runtime.CompilerServices.FormattableStringFactory. These were not available for my project - I guess they might not yet have made it into all platforms for CTP6.
This apparently made the compiler hang as described. Once I pulled the code for those two types from the CoreCLR code and added it to my project, my code works as expected.
This was figured out through code comments for the InterpolationTests. Hooray for the source being available :-)

.NET Reflector and getters/setters issue

I'm using an up-to-date .NET Reflector to disassemble an internal legacy app whose source code is almost impossible to recover. I need to find the cause of a nasty bug, and then possibly patch it. Reflector did a good job as usual in the re-creation of the project's structure, but soon I discovered that some property calls were left "expanded" to its get_() and set_() method signatures, rendering the source code impossible to compile.
At first, I thought that every get/set call had the problem. But at a closer look, several of them are OK, while others (especially OleDbCommand and Forms.Control properties) will be generated as get_() and set_().
A quick Visual Studio "Search/Replace" with regex solved these cases, but it's awkward. Is there a way to make Reflector behave correctly?
EDIT 1 - Sample problematic code below:
/* Generated by .NET Reflector 6.1.0.11 */
/* The variable selectCommand is a OleDbCommand. */
string parameterName = "#P" + Convert.ToString(num);
selectCommand.set_CommandText(selectCommand.get_CommandText() + " WHERE SIGLA = " + parameterName);
/*
Expected something like this (as ugly as it may seem):
selectCommand.CommandText = selectCommand.CommandText + " WHERE SIGLA = " + parameterName;
*/
EDIT 2 - The assembly was built in Release mode.
Where are you viewing the source code in Reflector? In the current version (6.1.0.11 at the time of this writing), disassembling a type then clicking on "Expand Methods" at the bottom yields a full class definition with code, including the correct property syntax (get { ... } and set { ... })
This problem appears with disassembling to Managed C++, right? Might want to disassemble to C# code (there is dropdown in the toolstrip) and you will get the usual properties.
So even if this question is quite old an a correct answer will never be achieved, you can now maybe give the the new tool on the block ILSpy a chance.
Maybe it will produce some better source code out of the box.

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

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?
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.
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.
You sort of can. The relevant function is MethodBase.GetMethodBody.
It's not exactly the most useful API. You can get some basic information about what's inside the method, and you can obtain the IL as a byte array. That's about it.
There's a slightly better API in the Mono.Cecil library, which exposes a MethodDefinition class with its own MethodBody implementation which contains actual Instructions, so you don't have to interpret the raw byte code. Still, if you're looking to get C# code out of it à la Reflector, you're going to be sorely disappointed. Also, Cecil isn't very well documented.
If you still want to try, then good luck.
If you don't need to do this real-time, have a look at Reflector. You can disassemble any .NET assembly (including the MS core DLLs) and see the code in your language of choice. This can be very educational.
Update Has anyone tried using Reflector on Reflector to figure out how this is done?
I'd like to provide an example of how one could explore the code inside a method. As others have explained, this can't be done easily using the native .NET Reflection API. However, using the Mono.Reflection API, you can disassemble the code programmatically using the GetInstructions() method and inspect it at runtime.
For example, the following code inspects a method and computes the number of calls inside it. As a use case for such a code, say I am a teacher (which I am) and instruct my fellow students to program a given method without using any other method, then using this code in unit tests I can verify that the given constrain is respected.
public static class MethodInfoUtil
{
public static int NbOfInnerCalls(this MethodInfo mi)
{
return mi.GetInstructions().Count(
instruction => instruction.OpCode.FlowControl == FlowControl.Call);
}
}
Example Console program:
class Program
{
static int Add(int a, int b) => a + b;
static int Doubling(int a) => Add(a, a);
static int Quadrupling(int a) => Add(Add(a, a), Add(a, a));
static void Main(string[] args)
{
Console.WriteLine("Inner method calls");
Console.WriteLine(" Add: {0}", ((Func<int, int, int>)Add).Method.NbOfInnerCalls());
Console.WriteLine(" Doubling: {0}", ((Func<int, int>)Doubling).Method.NbOfInnerCalls());
Console.WriteLine("Quadrupling: {0}", ((Func<int, int>)Quadrupling).Method.NbOfInnerCalls());
}
}
// Output:
// Inner method calls
// Add: 0
// Doubling: 1
// Quadrupling: 3
No
This is a feature slated for the next version of C#. You can use the CodeDom to get more info than reflection, but you cannot interrogate the parse tree yet.
Well there is always mono, in mono the compiler is a service, and you could get the parse trees at runtime.
The better question is why you want to?
Yes, there must be a way to achieve this: The .NET Reflector tool does this, too. Can't tell you how it's done there, though.

Categories