In some situations it can be important to know which methods are calling other methods. Think of an error log. Here you would like to know which method that threw the error and at what line in what file. This helps to debug runtime code and makes it very easy to find the exact point of failure.

C# 2.0 has the possibility to go back in time and inspect which methods called other methods all the way up the stack. Here is a static method that does just that and returns the caller of any method in the stack.

/// <summary>
/// Retrieves the caller of any method in the stack.
/// </summary>
/// <param name="skipFrames">How many steps to go back up the stack.</param>
/// <returns>The method name, file name and line number of any caller.</returns>
public static string GetCaller(int skipFrames)
{
  System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(skipFrames, true);
  string method = sf.GetMethod().ToString();
  int line = sf.GetFileLineNumber();

  string file = sf.GetFileName();
  if (file != null)
  {
    // Converts the absolute path to relative
    int index = file.LastIndexOf("\\") + 1;
    if (index > -1)
      file = file.Substring(index);
  }

  return method + " in file " + file + " line: " + line;

In a error logging scenario you probably want to set the skipFrames parameter to 1, which is the latest method or the method highest on the stack.

As a follow-up on my post from yesterday about generating shorter GUIDs, I’ve created a small helper class in C#. The class encodes a GUID into a 22 character long string and decodes the string back to the original GUID again.

That way you can save 10 characters from the original GUID and it is ASCII encoded so it will work perfectly in a URL as a query string or in ViewState.

It takes a standard GUID like this:

c9a646d3-9c61-4cb7-bfcd-ee2522c8f633

And converts it into this smaller string:

00amyWGct0y_ze4lIsj2Mw

using System;

public static class GuidEncoder
{
 public static string Encode(string guidText)
 {
  Guid guid = new Guid(guidText);
  return Encode(guid);
 }

 public static string Encode(Guid guid)
 {
  string enc = Convert.ToBase64String(guid.ToByteArray());
  enc = enc.Replace("/", "_");
  enc = enc.Replace("+", "-");
  return enc.Substring(0, 22);
 }

 public static Guid Decode(string encoded)
 {
  encoded = encoded.Replace("_", "/");
  encoded = encoded.Replace("-", "+");
  byte[] buffer = Convert.FromBase64String(encoded + "==");
  return new Guid(buffer);
 }
}

It basically just converts a GUID into a base64 string and shortens it a bit.