Get the current method and class without exception and without using reflection in C #

I want to exit any INFO log in a method, and I do not want to use reflection to get the name of the class and method.

To register errors, I can get the stack from the exception, but how to do it without exception to disable StackTrace?

+4
source share
3 answers

You can get caller information using caller attributes

public void Log(Exception ex, [CallerFilePath]string callerFilePath = null, [CallerMemberName]string callerMemberName = null, [CallerLineNumber]int callerLineNumber = 0)
{
    Console.WriteLine($"Message: {ex.Message} # File: {callerFilePath} # Line: {callerLineNumber} # Member: {callerMemberName}"  );
}

When the method is called, information about the caller will be passed to you by the compiler, you do not need to manually specify the parameters.

+8
source

Using reflection to get this data is quite expensive.

|               Method |          Mean |      Error |     StdDev |
|--------------------- |--------------:|-----------:|-----------:|
| MethodNameReflection | 1,452.4709 ns | 24.5287 ns | 50.6561 ns |
|     MethodNameNameOf |     0.0543 ns |  0.0521 ns |  0.0678 ns |
|             TypeName |    14.4099 ns |  0.3964 ns |  0.7543 ns |
|   TypeNameReflection | 1,659.5866 ns | 33.1575 ns | 90.7682 ns |

And code (using BenchmarkDotNet)

public class CurrentMethodInfoBenchmarks
{
    [Benchmark]
    public string MethodNameReflection() => MethodBase.GetCurrentMethod().Name;

    [Benchmark]
    public string MethodNameNameOf() => nameof(MethodNameNameOf);

    [Benchmark]
    public string TypeName() => GetType().Name;

    [Benchmark]
    public string TypeNameReflection() => MethodBase.GetCurrentMethod().DeclaringType.Name;
}

CallerMemberAttributes , nameof(), .

+2

you can use the System.Environment.StackTrace property

0
source

Source: https://habr.com/ru/post/1692763/


All Articles