Get the current line number in C#
This post will discuss how to get the current line number in C#.
C# compiler can obtain information about the caller to a method like the file path of the source code, the line number in the source code, and the member name of the caller using info attributes.
Starting with .NET 4.5, you can use the CallerMemberName, CallerFilePath and CallerLineNumber attributes defined in the System.Runtime.CompilerServices namespace. The CallerLineNumber attribute obtains the line number in the source file at which the method is called. For example, the following code shows how to use their usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Runtime.CompilerServices; public class Example { public static void DisplyCustomMessage(string msg, [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "") { Console.WriteLine($"Message: {msg}"); Console.WriteLine($"Source Line Number: {lineNumber}"); Console.WriteLine($"Caller Function: {memberName}"); Console.WriteLine($"Source file path: = {filePath}"); } public static void Main() { DisplyCustomMessage("Hello"); } } |
Output:
Message: Hello
Source Line Number: 19
Caller Function: Main
Source file path: = /box/Main.cs
That’s all about getting the current line number in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)