The Artima Developer Community
Sponsored Link

.NET Buzz Forum
A First Look at C# 6 - Nameof operator

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Christian Horsdal

Posts: 253
Nickname: horsdal
Registered: Mar, 2009

Christian Horsdal is a software architect at MjĂžlner Informatics.
A First Look at C# 6 - Nameof operator Posted: Nov 15, 2014 9:28 AM
Reply to this message Reply

This post originated from an RSS feed registered with .NET Buzz by Christian Horsdal.
Original Post: A First Look at C# 6 - Nameof operator
Feed Title: Horsdal
Feed URL: http://www.horsdal-consult.dk/feeds/posts/default
Feed Description: A blog that will be about code, architecture, design, and .NET.
Latest .NET Buzz Posts
Latest .NET Buzz Posts by Christian Horsdal
Latest Posts From Horsdal

Advertisement
This is the fourth post about the C# 6 features I used when moving Nancy.Linker over to C# 6. The first part was about primary constructors. The second part was about auto properties. The third was about expression bodied members. This one in about the new nameof operator.

The nameof operator

The new nameof operator is a unary operator that takes, as its argument, a type, an identifier or a method and returns the name of the argument. That is, if you pass in the type Uri, you get back the string "System.Uri", if you pass in a variable you get back the name of the variable as a string.

In Nancy.Linker there was one opportunity for using nameof, which I coincidentally think represents a usage of nameof that will become widespread.
In one the private methods in Nancy.Linker there is a null check followed by a possible ArgumentException:


Notice how I am repeating the name of the res variable in a string in order to tell the ArgumentException which argument is in error. With the nameof operator I avoid this duplication and potential source of inconsistency as follows:


Note that in case I rename res and forget to update the usage inside nameof I get a compile error.

Do I Like This?

Yes. It lets me have fewer magic strings.

Read: A First Look at C# 6 - Nameof operator

Topic: Watch out for superficial invariants Previous Topic   Next Topic Topic: Working Around SQL Server Standard Edition Limits

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use