Home >Backend Development >C++ >How Can I Get the Current Line Number in My C# Code?

How Can I Get the Current Line Number in My C# Code?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 21:54:11709browse

How Can I Get the Current Line Number in My C# Code?

Retrieving Current Line Number in Your Code

If you're working with code and want to know which line number is currently being executed, there's a solution for you.

You can accomplish this using the compiler's assistance in .NET 4.5 / C# 5. Here's how:

  1. Define a utility method that leverages the caller attributes:
using System.Runtime.CompilerServices;

static void SomeMethodSomewhere()
{
    ShowMessage("Boo");
}
  1. Create a method called ShowMessage that accepts a message, along with optional parameters for the caller's line number and member name:
static void ShowMessage(string message,
    [CallerLineNumber] int lineNumber = 0,
    [CallerMemberName] string caller = null)
{
     MessageBox.Show(message + " at line " + lineNumber + " (" + caller + ")");
}
  1. Call ShowMessage from your code:
SomeMethodSomewhere();

The output will display, for instance:

Boo at line 39 (SomeMethodSomewhere)

Additionally, if you need the path of the original code file, the [CallerFilePath] attribute can provide that information.

The above is the detailed content of How Can I Get the Current Line Number in My C# Code?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn