'Naming Conventions in C# - underscores
I saw this at an MVC3 Razor tutorial at http://www.asp.net
public ActionResult Index() {
return View(_usrs._usrList);
}
Isn't that usage plain wrong? I have always thought that [docs]
In C#, I usually see it used only when defining the underlying private member variable for a public property. Other private member variables would not have an underscore. This usage has largely gone to the wayside with the advent of automatic properties though.
Or is it a new naming convention I am seeing? Very curious about that usage in Microsoft's own tutorial.
P.S: The article is pretty good. Its just that I tend to follow naming conventions for better readability.
Solution 1:[1]
The guidelines are summarized here http://blogs.msdn.com/b/brada/archive/2005/01/26/361363.aspx and include the stipulation to use "this." instead of underscore. But I find that peppering my code with "this."'s makes the code more wordy, cluttered and hard-to-read. Furthermore it seems to be less often followed than underscore so as a convention, "_" seems more conventional.
Solution 2:[2]
In ASP. NET MVC 3 underscores are used more usually. For example all your partial views you need to name with underscore like _MyPartialView.
It's going for easy distinguishing partial views and views in your application.
Anyway, in this example I don't prefer sing underscores, because there is no need to use them. It isn't wrong, because it's good practice to write with underline lists of your entities. But I will prefer to write without them.
So both ways are right, write in the way you feel more comfortable.
Solution 3:[3]
With C# 7, we have a new use of underscore, indicating a "discarded" variable. This is common when using one of the TryParse methods -- we sometimes need either the return value or the out value, but not both. In C# 7, if you use "_" as the variable name, the compiler will optimize the object code to never create the variable at all. If you didn't need the output variable (you just wanted to know if the parse was successful) you might have a construction like this:
if (Int32.TryParse(input, out _))
Alternately, if you don't care about the parse success, only the output variable, you can assign that to _ like this:
_ = Guid.TryParse(input, out Guid id);
The underscore by itself is a legal variable name, so you can start using this pattern right away. Earlier versions of C# will just create a new variable with that name and not optimize the object code, but you will communicate to yourself and your fellow developers that the variable is unimportant to the function of your code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user316117 |
| Solution 2 | |
| Solution 3 | Michael Blackburn |
