The nameof
construct is a really great feature of C# 6.0, especially in ASP.NET Core: It avoids the usage of hard coded strings, like for action names. Instead we refer to a class/method, and get compining errors, if their naming changes.
Example:
public async IActionResult Home() {
return RedirectToAction(nameof(PageController.Index), GetControllerName(nameof(PageController)), new { Area = KnownAreas.Content });
}
Compared to the old version without nameof
public async IActionResult Home() {
return RedirectToAction("Index", "Page", new { Area = KnownAreas.Content });
}
As this is great, it blow up the code: For example I had to define a base controller class with GetControllerName
. This method removes the Controller
prefix, cause the controller is named Page
, not PageController
(the last case would result in a 404 because we double the Controller
suffix.
Since this is a common use case and I want to keep the code as clean as possible, I would like to reduce that call to something like this:
public async IActionResult Home() {
return RedirectToActionClean(PageController.Index, PageController, new { Area = KnownAreas.Content });
}
Or even the following (which seems not possible)
public async IActionResult Home() {
return RedirectToActionClean(PageController.Index, new { Area = KnownAreas.Content });
}
Internally, I want to use nameof
. So I pass PageController.Index
to my method, and I internally have this value as string. But this seems difficult, since nameof
seems to be a language construct, which can't be set as a type like generics.
To make it clear, lets have a look at my RedirectToActionClean
header:
void RedirectToActionClean(??????) {
}
The question is: What type can be used for the qestion marks, that I can pass any type without instance like on nameof
?
I think this is not possible since nameof
seems to be a language construct and not a type. But maybe I understood something wrong and there is a way to do this. I'm using ASP.NET Core 1.1 on the latest Visual Studio 2017 with C# 7.