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

Your email address will not be published. Required fields are marked *