Milkman Matty
09/12/2019

C# nameof

This is more of a note-to-self than anything else. The nameof operator in C# is super useful when adding in reporting or doing any type of deep debugging. Really anything that requires parameters can make use of the operator. One famous use case is the following:

switch (e.PropertyName){
    case nameof(SomeProperty):
    { break; }

    // opposed to
    case "SomeOtherProperty":
    { break; }
}

I must admit that most of my useage with the operator comes from self-reporting and error handling:


public void RunThing() {
    try { 
        RiskyThing();
    } catch (Exception e) {
        HandleError(e, nameof(this.RunThing));
    }
}

private void HandleError(Exception e, string caller = ""){
    //handle null input
    if(String.IsNullOrEmpty(caller)){
        caller = new StackTrace().GetFrame(1).GetMethod().Name;
    }

    //Log error
    db.ErrorLogs.Add(new ErrorLog({
        ErrorTypeID = Ref.ErrorType.General,
        DateCreated = DateTime.Now,
        Error = e.Message + "
" + (e.InnerException == null ? "" : e.InnerException.Message), Invoking = caller, StackTrace = e.StackTrace })); db.SaveChanges(); }

In most cases you could just write a hardcoded string instead of using the nameof operator, but the beauty of using the nameof operator is that if the method name ever changes a compile-time warning is generated.

Some things to keep in mind: