✅ Purpose and use of nameof() keyword
Hello guys, I have just came across the nameof() keyword so I read a bit about it. Can someone confirm whether the following statement is correct please (add up to it if need please). So, from what I've understood, nameof() is used to dynamically fetched the name of a variable without hardcoding it into a string? Like if we don't use nameof() and directly use the variable name, what happens is we don't fetch the variable name itself but the value it contains?
I noticed we also used in when throwing an exception, is there a reason for that? Or it's just to know which argument causes the error ?
10 Replies
nameof
is a convenient way to avoid magic strings. The whole idea is to ensure that there is clarification on what a string is, and also to keep it up to date.
For example, if I were to log a message about message Foo
, it is super convenient that I can use nameof(Foo)
because if the method were ever renamed, I am sure that instances where it was referenced is also updated. This would not be the case where I hardcode the name in a string because then you end up with the risk that this magic string refers to nothing in the future
There's no direct benefit to using it. If you never ever change the name of something it provides absolute nothing. It just ensures that the string passed continues to refer to the referred class/variable/method/whateverhmm when you say the instances will be updated, this is done automatically?
As for the exception, same reason. If you throw an ArgumentException you can pass the faulthy arguments. These take a string of the name of the argument and .NET then formats the message to reference these. Here you also have a case of ensuring the argument is properly passed and future renames remain consistent.
or we just have an error telling us this doesn't match anymore
It would error, because you reference something that does not exist anymore
And most IDEs have a rename function. if you use that it will also update the
nameof
instancesyep I see
You can imagine it is the same as renaming a variable that is used further down the code. The instance that uses it now uses a variable that is no longer defined
oh yeah, it's clearer now, thanks !
Be sure to $close when the question was ansered
If you have no further questions, please use /close to mark the forum thread as answered