Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
There are a few questions on this, but they all seemed to be targeting a specific part of the language;
What are the most common naming conventions in C#? - Asking specifically about getters/setters.
C# naming conventions for acronyms - Asking more specifically about short uppercase suffixes.
I'm just starting out in C# with a friend on a venture to create games for XBOX Live Arcade. I've developed a number of games using ActionScript 2 and 3 but want to start exploring more powerful languages and devices.
I want to ensure that I don't peeve people that I start working with (if I get to that) or even just people on here when I run into trouble and ask a question with seriously disturbing / "incorrect" naming of methods, etc.
I've found it confusing in the example code that I've seen because there seems to be from my current point of view some flaws. I doubt that a flawed naming convention would be used, so I realize that I'm just having trouble understanding.
As far as I can tell so far, there are these conventions:
public Type SomeMethod()
private Type SomeMethod() - no underscore or anything?
public static Type SomeMethod()
private static Type _SomeMethod() - this one just seems odd..
public Type someProperty - switching it up to camel casing for properties?
public static Type SomeProperty - and then going back to pascal casing for static..
In ActionScript 3, I have developed and strictly stick to these conventions:
private var _someVar
public var someVar
private function _someMethod()
public function someMethod()
public static var SomeStaticVar
public static function SomeStaticMethod()
public const SOME_CONSTANT
Is there a complete list of naming conventions with reasoning behind each so that I can get my head around them? The reversal of syntax (i.e. public Type method() instead of AS3's public function method():Type) is throwing me out enough at the moment that I know I need to keep an eye on how I'm naming things, otherwise I'll forget and develop bad habits, which I'd rather nail and avoid now.
The two main Capitalizations are called camelCase and PascalCase.
The basic rules (with lots of variations) are
Types use PascalCase
properties and methods always use PascalCase
public members (fields, consts) use PascalCase
local variables use camelCase
parameters use camelCase
And although the documentation states that "Internal and private fields are not covered by guidelines" there are some clear conventions:
private fields use camelCase
private fields that back a property prefix a _
There is the All-In-One Code Framework Coding Standards from Microsoft which contains a complete set of rules and guidelines. (also used to be available here)
This document describes the coding style guideline for native C++ and .NET (C# and VB.NET) programming used by the Microsoft All-In-One Code Framework project team.
There are a whole lot of naming conventions advocated by Microsoft for .Net programming. You can read about these here.
As a rule of thumb, use PascalCase for public property, method and type name.
For parameters and local variables, use camelCase.
For private fields, choose one: some use camelCase, other prefix _camelCase with an _.
A commonly seen convention is also to name constants with ALLCAPS.
C# prefers PascalCasing for classes, properties, and methods.
As far as I can tell so far, there are these conventions:
public Type SomeMethod() <-- yes
private Type SomeMethod() <-- correct, no underscore
public static Type SomeMethod() <-- correct
private static Type _SomeMethod() <-- this seems odd to me too. underscore should not be there
public Type someProperty <-- no, a public property should be PascalCased (SomeProperty)
public static Type SomeProperty - and then going back to pascal casing for static..
If you are using Visual Studio, or XNA Game Studio (which I think is a fork of Visual Studio), I highly recommend springing for a ReSharper license (from jetbrains software). They will tell you, in your code editor, how to conform to common C# conventions.
Addition:
You should use camelCasing for private fields and method arguments. For private fields, I usually prepend them _withAnUnderscore.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
If a class (or a structure) has a field and we replace it with an auto property of the same type, will client code always stay the same, taking into account that we don't use reflection or any other type of direct or indirect meta-programming? For example
int Integer;
public void Test() {
Console.WriteLine(Integer);
}
If I change int Integer to int Integer { get; set; }, the code that uses it stays unchanged. Is there any case when I need to change calling code?
The same question about readonly fields and get-only properties.
EDIT: I clarified my question. Also, taking into account existing answers, instead of auto property, question will be about ref property:
Is it possible to replace this
int Integer;
with
int _integer;
ref int Integer => ref _integer
Without any changes of calling code?
I want to find a case when I need to change client source code if I
replace a field with a property or opposite. I want to know how safe
this replacement is
Fields (C# Programming Guide)
Generally, you should use fields only for variables that have private
or protected accessibility. Data that your class exposes to client
code should be provided through methods, properties and indexers. By
using these constructs for indirect access to internal fields, you can
guard against invalid input values. A private field that stores the
data exposed by a public property is called a backing store or backing
field.
So there you have the official word on field and property usage
I mean, if we replace a field with auto property or opposite, do we
need to change client code in some cases
Yes, you are likely to break things in the following cases,
If you are exposing fields that are being passed by ref
If this class is being inherited and in cases where fields or properties are getting re-implemented or overridden
A derived classes implement Interfaces that require properties etc.
Also there could be cases where they are used in Expressions and it expects field or a property (I think).
In short, if large code bases relied on fields/properties and you change them this is likely to cause breakable changes for any of the above.
Though in summary, if you lived by the Microsoft recommendations above, you should have less of a problem, and if you do it points to the fact this should probably be refactored as a new version anyway (with breakable changes, and more expected usage).
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
My textbook (Visual C# How to Program, 6/e) states that fields in C# should use camelCase. This corresponds with examples given in Microsoft C# Guide:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/fields
public class CalendarEntry
{
// private field
private DateTime date;
// ...
}
However the official Microsoft naming convention clearly states that fields should use PascalCase (although they didn't provide an example of private fields as they normaly should be):
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions
Identifier: Field,
Casing: Pascal,
Example:
class MessageQueue
{
public static readonly TimeSpan InfiniteTimeout;
}
public struct UInt32
{
public const Min = 0;
}
Sooo, how do I know what case to use to keep my coding style right according to MS coding conventions?
AFAIK there is no set in stone convention for c#... Yes, there is technically an "official" convention, but it's not followed 100% of the time, even in MS's own source code, and it's certainly not religiously followed by many programmers and/or companies.
With that in mind, my preferred convention, and the best I've seen so far, is the one set by default in ReSharper. I strongly suggest following this convention:
PascalCase for: Classes, Structs, Methods, Properties, public | internal | protected Fields (regardless of static | readonly | const) and private const Fields.
_underscorePrefixCamelCase for: private _fields (except when const).
camelCase for: local variables.
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
After reading a lot about immutability in C#, and understading it's benefits (no side effects, safe dictionary keys, multithreading...) a question has come to my mind:
Why there is not a keyword in C# for asserting that a class (or struct) is immutable? This keyword should check at compile time that there is no way you can mutate the class (or struct). For example:
public immutable class MyImmutableClass
{
public readonly string field;
public string field2; //This would be a compile time error
public readonly AnyMutableType field3; //This would be a compile time error
public string Prop { get; }
public string Prop2 { get; set; } //This would be a compile time error
public AnyMutableType Prop3 { get; } //This would be a compile time error
}
I think the compiler work would be quite easy, as it would need to check just a few things:
All public fields are readonly.
All public properties only have getters.
All public fields or properties have immutable types as well (simple value types, or immutable classes/structs).
All public functions or public property getters only depend on immutable fields or properties (public fields/props as described before, or private fields/props which comply to the same restrictions). This of course includes Equals(), GetHashCode() and ToString().
Some possible problems come to my mind with this design:
For the compiler to know that a compiled class/struct is immutable, it would probably be necesary to make changes in the intermediate language.
Readonly generic collection (such as IEnumerable<T>) immutability would depend on the immutability of the type <T>. The proposed immutable keyword would not be useful in this context, as you could not declare that IEnumerable<string> is immutable, even though it is.
Are the reasons stated before enough for this keyword to not exist?
Am I missing any other drawbacks?
Is this just not necessary enough for such big changes in the language?
The short version would be: because nobody has proposed, spec'd, designed, implemented, tested, documented, translated and supported that feature.
The longer version would relate to why to do it, given that it can be achieved indirectly with the readonly field - what benefit would it add.
For classes, it turns out to be relatively minor. Note that there is an [ImmutableObject(true)] attribute that can be used, but no features or frameworks really have a use for it, so ... nobody uses it.
There was a proposal to add "readonly structs" in a future version of C# (related to ref locals, Span<T>, etc) - but: it died a death and evaporated. However, the ref readonly stuff lives on, which is intended to prevent reassignment of this in struct instance methods.
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 9 years ago.
Improve this question
Is there a standard or accepted code style for whether public or private members / functions come first in a class?
I expected to find a lot on Google regarding this but have found nothing.
Take a look at this SO question. It has the StyleCop Rules Documentation's requirements.
Fairly well used standard.
ASIDE: There is a free plugin for C#. Makes following the rules much simpler when you know what you are doing wrong. It will tell you if you violate the rules and can be set to run during the build step.
There are ordering rules with StyleCop which are useful to follow as a point of standardisation.
No this is simply a matter of personal preferences. Just follow your company one if that applies.
As people are saying, the order generally doesn't matter. However, there is one important exception, and that's initializing static fields. You can initialize static fields based on the value of other static fields - it all ends up getting compiled into the static constructor, but in the order that it's written in the code.
For example:
class Program {
private static int j = 4;
private static int i = Program.j;
static void Main(string[] args) {
Console.WriteLine(Program.i); // 4
}
}
But:
class Program {
private static int i = Program.j;
private static int j = 4;
static void Main(string[] args) {
Console.WriteLine(Program.i); // 0
}
}
So keep this case in mind if you decide to re-shuffle your members around. To be totally safe, you can put the initializations in the static constructor, like:
class Program {
private static int i;
private static int j;
static Program() {
Program.j = 4;
Program.i = Program.j;
}
}
There are rules enforced by StyleCop that I have seen many people use as a standard.
Frankly, they make sense1, but I don't think it's the best way.
I think things should be grouped by functionality, not by type, or accessibility, or static, etc. I would argue that a scheme that is organized by functionality requires the least amount of navigation when trying to read or maintain a code base. Any other ordering scheme (or *rules) would leave you navigating all over the class as you try to work with it. A conceptual ordering that places things together that make sense will minimize that jumping around. It's about making it easier to understand and work with it. It's a practical perspective, rather than forming rules for the sake of having rules that can be enforced.
1: They make sense in that they are a rule, they appeal to the OCD among us, and they can be enforced by a machine, but who cares if the machine can enforce them? But code is not for the machine, it is for the humans. When I need to understand the code, I don't think to myself "if only I could first understand all the constant fields, and then all the fields, etc." I take a very different approach. I want to see the big picture first, and one thing that is going to assist with that is seeing the code organized by functionality.
Here is the Microsoft C# Coding Conventions (C# Programming Guide)
It makes no mention of ordering for public, protected or private functions or members in a class.
I know in my past experience that FxCop had "suggested" that I put my public functions before my private functions, but again not necessarily a standard.
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 there is a debate/opinion about using this keyword or underscore in regards to private fields/properties (and I'll mention, I'm stuck on .NET 2.0)
Personally, I prefer this, but there are times you can't use it, for example when you need to reference a global variable from within a static method. Well, then we are forced to use the underscore (assuming we only have 2 choices, this or underscore). This means if my class uses any static methods I can't use this throughout the document.
Now, I've read the naming guidelines and used StyleCop, both would rather I don't use the underscore, but my Resharper pretty much insists on using _.
I don't feel it is right to have one class use the _ and the next class use this simply to accommodate for when the classes mixes non-static and static methods! The advice here on SO is to keep to one implementation/style but I don't know if that means I should ignore Microsoft (and I know MS don't always follow their own rules)!
It has been suggested to prefix with something else, similarish to Hungarian but prefix with globVariableName where glob indicates global. I hate this idea, it's too bespoke and won't be obvious to any other developer outside my team.
So, my question is, what is the best way to define global variables consistently? Since they are naming guides, may be I can just ignore (at least _ can be used consistently but it feels wrong to ignore the advice from the language creators).
Just use the class name in the same way you'd use "this", in a static class. Example follows:
public static class MyStatic
{
public static object Global;
public static void SomeMethod()
{
var theGlobal = MyStatic.Global;
}
}
public class MyNonStatic
{
public object Global;
public void SomeMethod()
{
var theGlobal = this.Global;
}
}
Note: I can't actually think of any other way to do it.
By global variables, I assume you mean const or static fields
I thing StyleCop used to encourage you to use ClassName.staticField for static and const fields, but it seems to have dropped that rule, at least by default. That is still a nice way to do it though.
Also, you can configure Resharper to play nicely with StyleCop.
I always use underscore for both static and instance variables.
For instance variables i use this.variable
For static variables i , sometimes, prefix them with the name of class, e.g., ClassName.variable
this is just my personal opinion;
I believe using this for every private variable is very useful; it has a positive effect on readability of the code. Also, when you are employing some DI constructor injection method, it enables you to use same variable without any confusion, which seems very proper.
public void SomeMethod(int someVariable)
{
this.someVariable = someVariable;
}
I prefer this instead of underscore; underscore seems pretty at first glance; but refering to the previous examples it has negative effect on readability.
I name static variables with the same way I name class variables; usage of this keyword lowers the risk of confusion between private and static variables.