DEV Community

Discussion on: Nameof in C#: Understanding the Usage

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

Thanks for sharing this operator. I hadn't heard of it.

I can't really see why your example of bad use is any worse than any other use. What is your threshold for deciding if a name is likely to change?

Collapse
 
bytehide profile image
ByteHide

This depends on the nature of your code and how often it changes. If you're working with code that's being regularly refactored or evolved, using 'nameof' makes more sense to prevent outdated string literals.

As for the example, it's demonstrating an unnecessary use of 'nameof'. The variable 'name' is defined locally and is not likely to change or need refactoring. Using 'nameof' here doesn't provide much benefit and could potentially make code more confusing to read, because it's not immediately clear that 'nameof(name)' will output the string literal 'name'.

The primary purpose of 'nameof' is to maintain clear and maintainable code, especially for class properties, method names, and other symbols that could change. Using it elsewhere may not provide extra value and could potentially make code harder to understand.

I hope this clarifies it. Thank you for your comment!