Why generated code in C# uses underscore? [closed] - c#

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know this might be a stupid question, but here it goes.
I always wrote my private members like privateMember and I've been reading a lot about naming conventions in C# because I noticed that a lot of the automatic generated code in visual studio use _variableName for private members. Everywhere I read, even in Microsoft documents, that you should use privateMember.
So, my question is, if the good practices says that I should write privateMember, as I do now, Why the heck Visual Studio generates classes with private members using underscore (_privateMember)?

Microsoft Code Conventions actually recommend against using underscores altogether. It is really personal preference. I would not use generated code as inspiration for my coding convention standard.
Do not use underscores, hyphens, or any other nonalphanumeric characters.
Maybe it's because it's generated code and not intended to be read by humans. ;-)

Not so long time ago when C# was raising to the market there was a concept that local variables should be leaded by a prefix _. This concept was not accepted by the community as in pure C the _ leads system variable/functions and the metadata are lead by __. So after few years, they now discourage to use that. But still you will find some believer that use this notation not because it is a fanatic but a lot of old C# applications contain this convention.
Why this is in VisualStudio ?
This might be related to the time gap it was designed. In those time this approach was suggested by language designers. So it is probably that no one changed that in the configuration for latest version.

Naming conventions aren't 100% agreed upon. This is one of those that some people like, some people are indifferent to, and some people hate. Certain people consider it better for instance variables to stand out, via their name, and this is one way to do that. Other people use this.instanceVariable rather than instanceVariable all of the time so that instance variables stand out, other people prepend something other than a '_' character, and some people just don't go out of their way to use any special distinction.
At the end of the day what's important is that you, and the other members of your team agree on a standard and are consistent with it. What the rest of the world chooses to do doesn't need to affect you.
It's also worth mentioning that the code snippets generated by Visual Studio, in most cases, can be configured to be in line with your team's coding practices.

It's just a convention they use, I do it too. You can ultimately name your private fields whatever you want. Prefixing it with an underscore just makes it easier to read IMO.

As a convention private fields were/is used as with underscore e.g. string _name;
The link will give you more info on guidelines for naming coventions by MS http://msdn.microsoft.com/en-us/library/ms229045.aspx

It's just the C# language convention so that in constructor you can use _varable instead of this.variable, when the constructor and field name is the same.
there are all c# naming conventions in
http://msdn.microsoft.com/en-us/library/ms229002.aspx
It's a mather of you if you follow the convention of the generated code.
Besisdes the recomendations many programmers use the same convention as the generated code.
Some programs that help you refactor the code also sugests you to follow that name convention for field names.

The underscore at the beginning is VS's way of showing that it is a privateMember. We keep the underscore at the beginning as a rule, but it is really a personal preference as to what naming convention you use. Just pick one and stick with it so you don't confuse yourself or anyone else that might look at your code.

Related

Why do some languages prefer static method binding rather than dynamic? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Why is the default decision in C++, C#, and Ada 95 to use static method binding, rather than dynamic method binding.?
Is the gain in implementation speed worth the loss in abstraction and re-usability?
In general, you can consider that you have todesign the base class for extensibility. If a member function (to use the C++ vocabulary) isn't designed to be overridden, there is a good chance than overriding it will in practice not be possible and for sure it won't it be possible without knowledge of what the class designer think is implementation details and will change without giving you prior notice.
Some additional considerations for two languages (I don't know C# enough to write about it):
Ada 95 would have had compatibility issues with Ada 83 if the choice was different. And considering the whole object model of Ada 95, doing it differently would have make no sense (but you can consider that compatibility was a factor in the choice of the object model).
For C++, performance was certainly a factor. The you don't pay for what you don't use principle and the possibility to use C++ just as a better C was quite instrumental in its success.
The obvious answer is because most functions shouldn't be virtual. As AProgrammer points out, unless a function has been designed explicitly to be overridden, you probably can't override it (virtual or not) without breaking class invariants. (When I work in Java, for example, I end up declaring most functions final, as a matter of good engineering. C++ and Ada make the right decision: the author must explicitly state that the function is designed to be overridden.
Also, C++ and (I think) Ada support value semantics. And value semantics doesn't work well with polymorphism; in Java, classes like java.lang.String are final, in order to simulate value semantics for them. Far to many applications programmers, however, don't bother, since it's not the default. (In a similar manner, far too many C++ programmers omit to inhibit copy and assignment when the class is polymorphic.)
Finally, even when a class is polymorphic, and designed for inheritance, the contract is still specified, and in so far as is reasonable, enforced, in the base class. In C++, typically, this means that public functions are not virtual, since it is the public functions which define and enforce the contract.
I can't speak about Ada, but for C++ two important goals for the design of C++ were:
backwards compatibility with C
you should pay nothing (to the extent possible) for features that you don't use
While neither of these would necessarily dictate that dynamic binding couldn't have been chosen to be the default, having static method binding (I assume you mean non-virtual member functions) does seem to 'fit' better with these design goals.
I'll give one of the other two thirds of Michael Burr's answer.
For Ada it was an important design goal that the language be suitable for system's programming and use on small realtime embedded devices (eg: missile and bomb CPUs). Perhaps there are now techniques that would allow dynamic languages to do such things well, but there certianly weren't back in the late 70's and early 80's when the language was first being designed. Ada95 of course could not radically deviate from the orginal language's basic underlying design, any more than C++ could from C.
That being said, both Ada and C++ (and certianly C# as well?) provide a way to do dynamic method binding ("dynamic dispatch") if you really want it. In both it is accesed via pointers, which IMHO are kind of error-prone. It can also make things a bit of a pain to debug, as it is tough to tell from sources alone exactly what is getting called. So I avoid it unless I really need it.

Who Writes Microsoft Support Articles? Can They Always Be Trusted? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Here is an example of the type of article I'm talking about:
http://support.microsoft.com/kb/319401
I assume these articles are written by people who work for Microsoft and that the code in the articles will always be rock solid and never contain any malicious code. I just want to make sure I can explain to my boss that this is an ok place to copy code from (I've been told never to copy code from the internet, but this seems like a safe source).
I would trust them not to be malicious, but they're not always good code. (MSDN samples are sometimes pretty awful.)
For example, here's some code in the sample you gave:
compareResult = ObjectCompare.Compare
(listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
Now, there are two issues here:
Why is it deemed valid to have a comparer with no sort order? This should be a constructor parameter, validated at the point of construction IMO.
You should not just negate the result of one comparison to perform a "reverse comparison". That breaks if the result of the first comparison is int.MinValue - because -int.MinValue == int.MinValue. It's better to reverse the arguments used to perform the original comparison.
There are other things I'd take issue with in this code, but these two should be enough to make my point.
I heartily agree with the other answers too, in terms of:
- Check the copyright / licence etc of any code you want to use
- Make sure you understand anything you want to use
Your boss probably wouldn't mind if you only copied the code into a test project that you use to test and understand the code. You can then use what you've learned to write the production code.
And while I don't think anyone outside of Microsoft knows the names of the people who write those support articles, they come from the same vendor that your toolchain does, so if you don't trust the support articles, then you can't trust the tools you've bought either.
Microsoft Knowledgebase articles show safe (as in non-malicious but not necessarily secure) code, but usually the example provides the most basic use case possible. There's a good chance that you'll have to tweak the code a bit for it to work the way you want.
You should also pay attention to the date of the articles. For example, the article you link to is almost three years old. There's definitely a better way to handle that situation now.
Be aware that most codes in articles are there to help you understand the concepts. They are not "production ready". Learn the concepts instead and implement your own.
Have you been told not to copy code from the internet because of rights issues? If so then you don't have to worry about this Microsoft code.
I would advise you not to use any code you don't understand. If you can't say if the code is malicious or not don't use it.
MSDN and kb support articles are written by MS employees that are part of the given product's UX team (user experience). These are people who typically have a background in technical writing, but are not necessarily developers themselves (although some are). It's very common for the UX team to collaborate with developers on the product to ensure their code samples are correct. However this collaboration in my experience is one of the lowest priorities a typical MS developer has and can go ignored, and so it can at times lead to poor code getting out.
With that said, I completely agree with Carl Norum's comment. Copying code you do not understand is done at your own risk. Make sure you understand any code you place in your product!
I've always found the Microsoft articles to be of the highest quality (sadly not their products).
However, there's always the danger of a spoofing site.
Explain that you carefully read the article to understand the information in there, and only copy code that you understand.
If you don't understand the code, then even if the code is correct it may not be doing what you actually need done, thus your program will be incorrect.
You also will have a hard time debugging and maintaining code if there are parts that you don't understand.

Coding guidelines + Best Practices? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I couldn't find any question that directly applies to my query so I am posting this as a new question. If there is any existing discussion that may help me, please point it out and close the question.
Question:
I am going to do a presentation on C# coding guidelines but it is not supposed to limit to coding standards.
So I have a rough idea but I think I need to address good programing practices. So the contents will be something like this.
Basic coding standards - Casing, Formatting etc.
Good practices - Usage of Hashset over other data structures, String vs String Builder, String's immutability and using them effectively etc
Really I would like to add more good practices (Especially to improve the performance.) So like to hear some more good practices to be used with C#. Any suggestions??? (No need of large descriptions :) Just the idea is sufficient.)
Coding Guidelines for CSharp 3.0 and 4.0
IDesign Coding Standards
Lance Hunt's C# Coding Standards
Brad Abrams' Internal Coding Guidelines
Unsurprisingly, I just found a SO question: C# Coding standard / Best practices
Here are a few tips:
Use FxCop for static analysis.
Use StyleCop for coding style validation.
Because of the different semantics of value types, supply them with an alternative color in the IDE (go to Tools / Options / Environment / Fonts and Colors / Display Items and supply User Types (Enums) and User Types (Value types) with a value like #DF7120 [223, 113, 32]).
Because exceptions tend to show bugs in your code, let the IDE break on all exceptions. (go to Debug / Exceptions... / Common Language Runtime Exceptions and check Throw).
Project settings: Disallow unsafe code.
Project settings: Threat warnings as errors.
Project settings: Check for arithmetic overflow/underflow.
Use variables for a single, well defined goal.
Don't use magic numbers.
Write short methods. A method should only contain one level of abstraction.
A method can never be too small (a method of 20 lines is considered pretty big).
A method should protect itself against bad input.
Consider making a type immutable.
Don't suppress warnings in your code with pragma warning disable.
Don't comment bad code: rewrite it.
Document explicitly in code why you are swallowing an exception.
Note the performance implications of concatenating strings.
Never use goto statements.
Fail early, fail fast.
I'm using Microsoft's Design Guidelines for Developing Class Libraries.
And I think it is quite good to start with.
Basic Coding Standards - Make sure it's consistent. Even if they don't follow the conventions set out in this document on msdn. I think consistency is really key here.
Unit Tests - You cannot go wrong here.
Security - Talk about ensuring that if you are passing sensitive data around that it's secure.
Performance - You know, I personally feel that getting the application right and then looking at performance is what I do. I do have it in the back of my mind when writing code, so it's little fine tunings that come in at the end.

Underscores for private local variables? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 13 years ago.
It seems to be the case with the BCL to use underscores for private local variables. I never use them, but get away like this:
int count = 0;
this.Count++;
public int Count
...
public ClassName ( int count )
{
this.Count = count;
}
What are your thoughts on this? Are they are problems with my approach?
This is basically something you'll have to decide upon yourself, just find or make a style guide and follow it.
Personally, I use _ as a prefix for private fields of the class.
The simple rule we use here is: Private implementation details of a class, including variable names, are completely up to the developer who makes it. Public/protected method names, properties, class names, and so on, are subject to best practice guidelines. Internal types can even be considered to be part of this, since they are not publically visible.
When someone else needs to use your library, it will never have to work with internal or private types, will not see if you used underscores, etc. In other words, this is really up to you....
Just keep in mind that if someone else has to maintain your code later that it should not be too obfuscated...
It's not required to use the underscore to denote private variables. It's all personal preference. I use them only so I know I'm using the local variable rather than having Intellisense accidentally use my public Property instead.
IMO, you should never name a private member variable the same as the name of a property, method, or anything else, for that matter. It should be clear which named item you are working with. This will make your code easier to understand and maintain, and will reduce programming errors by yourself, or other developers who need to maintain your code.
Also, if you ever wanted to port the code to VB, that particular naming would not work. Not sure why you would want to switch to VB, but it happens.
I use underscores. It helps me keep variable scope in check and reduce the possibility naming collisions.
Underscores make more sense for languages that are not case sensitive (like VB.Net). In languages like C#, it comes down purely to personal preference.
If you have an aversion to putting this. in the front of some ambiguous assignments, then underscores are for you. Without them, you can occasionally accidentally do things like this:
private int that;
public void AssignThat(int that)
{
that = that; // assigns to method scope variable, not instance scope
}
FXCop or R# should catch this for you, and I believe you get a compiler warning, but it is possible.
There is a practical reason to use a prefix, IntelliSense. ATM it is braindamaged in the way that it does not really distinguish between current instance variables and inherited properties/variables. So using '_' for private variables makes it easier to locate variable within intellisense list and function/variable list in VS code editor. So in a way it is wider-scope hungarian notation.

XML Commenting tips for C# programming [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Good morning, afternoon, evening or night (depending on your timezone).
This is just a general question about XML commenting within C#. I have never been very big into commenting my programs, I've always been more of a verbose variable/property/method namer and letting the code speak for itself. I do write comments if I'm coding something that is fairly confusing, but for the most part I don't write alot of comments.
I was doing some reading about XML comments in .NET, Sandcastle, and the help file builder on codeplex and it has taken me down the path of wanting to document my code and generate some nice, helpful documentation for those who have to dig into my code when I'm no longer here.
My question is about standards and conventions. Is there a guide to "good" XML commenting? Should you comment EVERY variable and property? EVERY method? I'm just basically looking for tips on how to write good comments that will be compiled by sandcastle into good documentation so other programmers don't curse my name when they end up having to work on my code.
Thank you in advance for your advice and suggestions,
Scott Vercuski
Personally, we make sure that every public and protected method has XML comments. It also will provide you with Intellisense, and not just end-user help documentation. In the past, we also have included it on privately scoped declarations, but do not feel it is 100% required, as long as the methods are short and on-point.
Don't forget that there are tools to make you XML commenting tasks easier:
GhostDoc - Comment inheritance and templating add-in.
Sandcastle Help File Builder - Edits the Sandcastle projects via a GUI, can be run from a command line (for build automation), and can edit MAML for help topics not derived from code. (The 1.8.0.0 alpha version is very stable and very improved. Have been using it for about a month now, over 1.7.0.0)
Comments are very often outdated. This always has been a problem. My rule of thumb : the more you need to work to update a comment, the faster that comment will be obsolete.
XML Comments are great for API development. They works pretty well with Intellisens and they can have you generate an HTML help document in no time.
But this is not free: maintaining them will be hard (look at any non-trivial example, you will understand what I mean), so they will tend to be outdated very fast. As a result, reviewing XML Comments should be added to your code review as a mandatory check and this check should be performed every time a file is updated.
Well, since it is expensive to maintain, since a lot of non private symbols (in non-API development) are used only by 1 or 2 classes, and since these symboles are often self-explanatory, I would never enforce a rule saying that every non-private symbol should be XML commented. This would be overkill and conterproductive. What you will get is what I saw at a lot of places : nearly empty XML Comments adding nothing to the symbole name. And code that is just a little less readable...
I think that the very, very important guide line about comments in normal (non-API) code should not be about HOW they should be written but about WHAT they should contain. A lot of developers still don't know what to write. A description of what should be commented, with examples, would do better for your code than just a plain : "Do use XML Comments on every non-private symbole.".
I document public classes and the Public/Protected Members of those classes.
I don't document private or internal members or internal classes. Hence variables (I think you mean fields) because they are private.
The objective is to create some documentation for a developer who does not have ready access to the source code.
Endeavour to place some examples where usage is not obvious.
I very rarely comment on method variables, and equally rarely fields (since they are usually covered by a property, or simply don't exist if using auto-implemented properties).
Generally I try hard to add meaningful comments to all public/protected members, which is handy, since if you turn on the xml comments during build, you get automatic warnings for missing comments. Depending on the complexity, I might not fill out every detail - i.e. if it is 100% obvious what every parameter has to do (i.e. there is no special logic, and there is only 1 logical way of interpreting the variables), then I might get lazy and not add comments about the parameters.
But I certainly try to describe what methods, types, properties, etc represent/do.
We document the public methods/properties/etc on our libraries. As part of the build process we use NDoc to create an MSDN-like web reference. It's been very helpful for quick reference and lookup.
It's also great for Intellisense, especially with new team members or, like you said, when the original author is gone.
I agree that code, in general, should be self-explanatory. The XML documention, to me, is more about reference and lookup when you don't have the source open.
Personally my opinion is to avoid commenting. Commenting is dangerous. Because in industry we always update code(because business & requirements are always changing), but vary rarely we update our comments. This may misguide the programmers.

Categories