Letโs say you have a utility function thatโs used by multiple other functions to โdo the thing,โ and you want to log or print which function actually called this utility. How would you do that?
For example, consider a function that extracts the user ID from a JWT token:
public static string ExtractUserIdFromJWT(string jwtToken)
{
// extract user id from jwt token
return "";
}
Now, we want to log who the caller of this method isโso that if an error occurs, we know where the problem originated.
One way to do this is by using the Caller Information Attributes introduced in C# 5.
Hereโs how our extractor method could look:
public static string ExtractUserIdFromJWT(string jwtToken, [CallerMemberName]string callerMethod = "")
{
// extract user id from jwt token
Console.WriteLine($"called from ${callerMethod}");
return "";
}
And we can call it like this:
var userId = ExtractUserIdFromJWT(userJwtToken);
Now, imagine this ExtractUserIdFromJWT method is called from multiple places, and we also want to know exactly where the call originated.
You might think of passing the line number as an additional parameter โ but thatโs not ideal.
Instead, C# provides another handy attribute called [CallerLineNumber]. You can decorate a parameter with it to automatically capture the line number of the call.
Hereโs an updated version:
string ExtractUserIdFromJWT(string jwtToken,
[CallerMemberName]string callerMethod = "",
[CallerLineNumber]int lineNumber = -1)
{
// extract user id from jwt token
Console.WriteLine($"called from ${callerMethod} at line: {lineNumber}");
return "";
}


Leave a Reply