C# 5.0 [Caller Information Attribute]

If you’re using C# 5, you can use caller information attributes to do this. For example:

 using System;
 using System.IO;
 using System.Runtime.CompilerServices;

public class Test
 static void Log(string message,
 [CallerFilePath] string file = null,
 [CallerLineNumber] int line = 0)
 Console.WriteLine("{0} ({1}): {2}", Path.GetFileName(file), line, message);

static void Main()
 Log("Hello, world");
 Log("This is the next line");


 Test.cs (16): Hello, world
 Test.cs (17): This is the next line

Before C# 5, you’re stuck with execution-time stack checking, which is less reliable due to inlining, and relies on the information being present at execution time. (It might not in a release build, for example, whereas the above will still work.)

Schreibe einen Kommentar