Sunday, August 9, 2015

Converting existing code to use nameof() in C# 6

Now with the new C#6 nameof operator, the use of ArgumentNullExceptions and ArgumentExceptions become more flexible and resistant to variable refactoring and renaming.

ArgumentNullException

Here's a regex to search and replace in Visual Studio usage of ArgumentNullException: Search for:
throw new ArgumentNullException("(?<message>.*?)
Replace with:
throw new ArgumentNullException(nameof(${varname})

For example this will replace this
throw new ArgumentNullException("variable", "This variable cannot be null.");
with
throw new ArgumentNullException(nameof(variable), "This variable cannot be null.");

ArgumentException

Here's another regex to search and replace usage of ArgumentException: Search for:
throw new ArgumentException\("(?<message>.*?)", "(?<varname>.*?)"
Replace with:
throw new ArgumentException("${message}", nameof(${varname})
For example this will replace this
throw new ArgumentException("This argument is invalid for some weird reason.", "variable");
with
throw new ArgumentException("This argument is invalid for some weird reason.", nameof(variable));

No comments:

Post a Comment