Search code examples
.netkeywordstring-literals

How can I get any expression in C# as string?


In many cases one needs the name of an expression, parameter, statement, etc. For example:

public abstract void Log(string methodName, string parameterName, string message);

public void FooMethod(string value)
{
    if (value == null)
    {
        this.Log("FooMethod", "value", "The value must be whatever...");
        throw new ArgumentNullException("value");
    }

    if (value.Length < 5)
    {
        this.Log("FooMethod", "value.Length", "The value length must be whatever...");
        throw new ArgumentException("value");
    }
}

Is there any way of getting these string literals automatically like for example with a keyword that can be used like typeof(string)? Or is there a simple and performant approach based on reflection?

I'm not looking for a way to check and log this parameter (which is actually only an example). I'm looking for a method to get part of the code as string.

The following would be more accurate, could be checked by the compiler and would also be considered when refactoring the code:

public void FooMethod(string value)
{
    if (value == null)
    {
        this.Log(literal(this.FooMethod), literal(value), "The parameter '" + literal(value) + "' must be whatever...");
        throw new ArgumentNullException(literal(value));            
    }

    if (value.Length < 5)
    {
        this.Log(literal(this.FooMethod), literal(value.Length), "The value length must be whatever...");
        throw new ArgumentException(literal(value));
    }
}

Solution

  • You can create static methods like this for all possible types. Below is for method name.

    public static string GetString(Action obj)
    {
        return obj.Method.Name;
    }
    
    public static string GetString(Delegate obj )
    {
        return obj.Method.Name;
    }