Use of 'nameof' in C#
Magic strings vs. "nameof" property
Usage of magic strings - that's text with quotations - is quite bothersome when maintaining code.
For example, say we have a class Person.
public class Person { public string Name { get; set; } public DateTime BirthDate{ get; set; } ... public string Country{ get; set; } }
Let's say we need to build a name value collection for each of the fields of Person class. Traditionally we would write magic strings to build the name value collection as shown below:
public NameValueCollection GetValue(Person person) { var nvc = new NameValueCollection(); nvc.Add("Name", person.Name); nvc.Add("BirthDate", person.BirthDate); ... nvc.Add("Country", person.Country); }
This works until there are no changes in the field names apart from the fact that it is a cumbersome process to copy each field name as a magic string.
Now let's try using nameof:
public NameValueCollection GetValue(Person person) { var nvc = new NameValueCollection(); nvc.Add(nameof(person.Name), person.Name); nvc.Add(nameof(person.BirthDate), person.BirthDate); ... nvc.Add(nameof(person.Country), person.Country); }
Using nameof, our code is much cleaner and can withstand any change to the field names.
Other uses
- To retrieve enum values; Using nameof is much faster compared to using ToString():
var value = nameof(MyEnum.FooBar);
- HTML Action link parameters in MVC:
return RedirectToAction(nameof(HomeController.Index));
- MVC controller redirects:
<%= Html.ActionLink("Sign up", @typeof(UserController), @nameof(UserController.SignUp))%>
- ArgumentNullException parameter:
throw new ArgumentNullException(nameof(name));
- To retrieve property names while logging/auditing
- Any place in the code we need property names
If used the right way, nameof can produce cleaner code faster that is also easy to maintain. It is a simple feature that improves our coding experience.