C#

nameof vs ToString() in C#: Names, Values and Null Traps

C# Corner Shubham Sidnale
C#

A short walkthrough of how nameof and ToString() differ: one is resolved by the compiler and gives you an identifier, the other runs at runtime and gives you a value as text. It covers null handling, refactoring safety and where each belongs in exceptions and logging.

Key points

  • nameof is a compile-time operator; ToString() is a runtime method call.
  • nameof(employeeId) returns "employeeId"; employeeId.ToString() returns "101".
  • nameof works on a null variable, while ToString() on null throws NullReferenceException.
  • nameof(System.Console.WriteLine) returns only "WriteLine", not the qualified name.
  • Use nameof for ArgumentException parameter names and structured log templates.
  • Override ToString() to control how your own types appear in logs and debuggers.

Why it matters

Picking the wrong one either produces a runtime NullReferenceException or leaves hardcoded strings that silently break after a rename, so this is cheap insurance for large codebases.

Real-world use

  • An ASP.NET Core Web API that passes nameof(employeeName) to ArgumentException so validation messages stay correct after a rename.
  • Structured logging with ILogger templates that inject nameof(GetEmployeeAsync) as the method name next to runtime values.
  • Debugging sessions where a custom ToString() override prints an object's fields instead of its type name.
  • Code reviews catching ToString() used to recover a variable name or serialize an object for an API response.

This summary was generated by the agent from the original post on C# Corner. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message