Convert typeof
to nameof
This refactoring applies to:
- C#
- Visual Basic
What: Lets you convert an instance of typeof(<QualifiedType>).Name
to nameof(<QualifiedType>)
in C# and an instance of GetType(<QualifiedType>).Name
to NameOf(<QualifiedType>)
in Visual Basic.
When: All instances of typeof(<QualifiedType>).Name
where someType
isn't a generic type. This exclusion is necessary because this case doesn't return the same string value as nameof(<QualifiedType>)
. The same is true for the Visual Basic instance.
Why: Using nameof
rather than the name of the type
avoids the reflection involved with retrieving a type
object, and is a more pragmatic way of writing it.
How-to
Place your cursor within the
typeof(<QualifiedType>).Name
instance for C# or theGetType(<QualifiedType>).Name
in Visual Basic.Press Ctrl+. to trigger the Quick Actions and Refactorings menu.
Select from one of the following options:
C#
Select Convert 'typeof' to 'nameof':Visual Basic
Select Convert 'GetType' to 'NameOf':