c_sharp_style_guide.rst 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. .. _doc_c_sharp_styleguide:
  2. C# style guide
  3. ==============
  4. Having well-defined and consistent coding conventions is important for every project, and Godot
  5. is no exception to this rule.
  6. This page contains a coding style guide, which is followed by developers of and contributors to Godot
  7. itself. As such, it is mainly intended for those who want to contribute to the project, but since
  8. the conventions and guidelines mentioned in this article are those most widely adopted by the users
  9. of the language, we encourage you to do the same, especially if you do not have such a guide yet.
  10. .. note:: This article is by no means an exhaustive guide on how to follow the standard coding
  11. conventions or best practices. If you feel unsure of an aspect which is not covered here,
  12. please refer to more comprehensive documentation, such as
  13. `C# Coding Conventions <https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions>`_ or
  14. `Framework Design Guidelines <https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines>`_.
  15. Language specification
  16. ----------------------
  17. Godot currently uses **C# version 7.0** in its engine and example source code. So, before we move to
  18. a newer version, care must be taken to avoid mixing language features only available in C# 7.1 or
  19. later.
  20. For detailed information on C# features in different versions, please see
  21. `What's New in C# <https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/>`_.
  22. Formatting conventions
  23. ----------------------
  24. * Use line feed (**LF**) characters to break lines, not CRLF or CR.
  25. * Use **UTF-8** encoding without a `byte order mark <https://en.wikipedia.org/wiki/Byte_order_mark>`_.
  26. * Use **4 spaces** instead of tabs for indentation (which is referred to as "soft tabs").
  27. * Consider breaking a line into several if it's longer than 100 characters.
  28. Line breaks and blank lines
  29. ---------------------------
  30. For a general indentation rule, follow `the "Allman Style" <https://en.wikipedia.org/wiki/Indentation_style#Allman_style>`_
  31. which recommends placing the brace associated with a control statement on the next line, indented to
  32. the same level:
  33. .. code-block:: csharp
  34. // Use this style:
  35. if (x > 0)
  36. {
  37. DoSomething();
  38. }
  39. // NOT this:
  40. if (x > 0) {
  41. DoSomething();
  42. }
  43. However, you may choose to omit line breaks inside brackets:
  44. * For simple property accessors.
  45. * For simple object, array, or collection initializers.
  46. * For abstract auto property, indexer, or event declarations.
  47. .. code-block:: csharp
  48. // You may put the brackets in a single line in following cases:
  49. public interface MyInterface
  50. {
  51. int MyProperty { get; set; }
  52. }
  53. public class MyClass : ParentClass
  54. {
  55. public int Value
  56. {
  57. get { return 0; }
  58. set
  59. {
  60. ArrayValue = new [] {value};
  61. }
  62. }
  63. }
  64. Insert a blank line:
  65. * After a list of ``using`` statements.
  66. * Between method, properties, and inner type declarations.
  67. * At the end of each file.
  68. Field and constant declarations can be grouped together according to relevance. In that case, consider
  69. inserting a blank line between the groups for easier reading.
  70. Avoid inserting a blank line:
  71. * After ``{``, the opening brace.
  72. * Before ``}``, the closing brace.
  73. * After a comment block or a single-line comment.
  74. * Adjacent to another blank line.
  75. .. code-block:: csharp
  76. using System;
  77. using Godot;
  78. // Blank line after `using` list.
  79. public class MyClass
  80. { // No blank line after `{`.
  81. public enum MyEnum
  82. {
  83. Value,
  84. AnotherValue // No blank line before `}`.
  85. }
  86. // Blank line around inner types.
  87. public const int SomeConstant = 1;
  88. public const int AnotherConstant = 2;
  89. private Vector3 _x; // Related constants or fields can be
  90. private Vector3 _y; // grouped together.
  91. private float _width;
  92. private float _height;
  93. public int MyProperty { get; set; }
  94. // Blank line around properties.
  95. public void MyMethod()
  96. {
  97. // Some comment.
  98. AnotherMethod(); // No blank line after a comment.
  99. }
  100. // Blank line around methods.
  101. public void AnotherMethod()
  102. {
  103. }
  104. }
  105. Using spaces
  106. ------------
  107. Insert a space:
  108. * Around a binary and tertiary operator.
  109. * Between an opening parenthesis and ``if``, ``for``, ``foreach``, ``catch``, ``while``, ``lock`` or ``using`` keywords.
  110. * Before and within a single line accessor block.
  111. * Between accessors in a single line accessor block.
  112. * After a comma which is not at the end of a line.
  113. * After a semicolon in a ``for`` statement.
  114. * After a colon in a single line ``case`` statement.
  115. * Around a colon in a type declaration.
  116. * Around a lambda arrow.
  117. * After a single-line comment symbol (``//``), and before it if used at the end of a line.
  118. Do not use a space:
  119. * After type cast parentheses.
  120. * Within single line initializer braces.
  121. The following example shows a proper use of spaces, according to some of the above mentioned conventions:
  122. .. code-block:: csharp
  123. public class MyClass<A, B> : Parent<A, B>
  124. {
  125. public float MyProperty { get; set; }
  126. public float AnotherProperty
  127. {
  128. get { return MyProperty; }
  129. }
  130. public void MyMethod()
  131. {
  132. int[] values = {1, 2, 3, 4}; // No space within initializer brackets.
  133. int sum = 0;
  134. // Single line comment.
  135. for (int i = 0; i < values.Length; i++)
  136. {
  137. switch (i)
  138. {
  139. case 3: return;
  140. default:
  141. sum += i > 2 ? 0 : 1;
  142. break;
  143. }
  144. }
  145. i += (int)MyProperty; // No space after a type cast.
  146. }
  147. }
  148. Naming conventions
  149. ------------------
  150. Use **PascalCase** for all namespaces, type names and member level identifiers (i.e. methods, properties,
  151. constants, events), except for private fields:
  152. .. code-block:: csharp
  153. namespace ExampleProject
  154. {
  155. public class PlayerCharacter
  156. {
  157. public const float DefaultSpeed = 10f;
  158. public float CurrentSpeed { get; set; }
  159. protected int HitPoints;
  160. private void CalculateWeaponDamage()
  161. {
  162. }
  163. }
  164. }
  165. Use **camelCase** for all other identifiers (i.e. local variables, method arguments), and use
  166. an underscore (``_``) as a prefix for private fields (but not for methods or properties, as explained above):
  167. .. code-block:: csharp
  168. private Vector3 _aimingAt; // Use a `_` prefix for private fields.
  169. private void Attack(float attackStrength)
  170. {
  171. Enemy targetFound = FindTarget(_aimingAt);
  172. targetFound?.Hit(attackStrength);
  173. }
  174. There's an exception with acronyms which consist of two letters, like ``UI``, which should be written in
  175. uppercase letters where PascalCase would be expected, and in lowercase letters otherwise.
  176. Note that ``id`` is **not** an acronym, so it should be treated as a normal identifier:
  177. .. code-block:: csharp
  178. public string Id { get; }
  179. public UIManager UI
  180. {
  181. get { return uiManager; }
  182. }
  183. It is generally discouraged to use a type name as a prefix of an identifier, like ``string strText``
  184. or ``float fPower``, for example. An exception is made, however, for interfaces, which
  185. **should**, in fact, have an uppercase letter ``I`` prefixed to their names, like ``IInventoryHolder`` or ``IDamageable``.
  186. Lastly, consider choosing descriptive names and do not try to shorten them too much if it affects
  187. readability.
  188. For instance, if you want to write code to find a nearby enemy and hit it with a weapon, prefer:
  189. .. code-block:: csharp
  190. FindNearbyEnemy()?.Damage(weaponDamage);
  191. Rather than:
  192. .. code-block:: csharp
  193. FindNode()?.Change(wpnDmg);
  194. Implicitly typed local variables
  195. --------------------------------
  196. Consider using implicitly typing (``var``) for declaration of a local variable, but do so
  197. **only when the type is evident** from the right side of the assignment:
  198. .. code-block:: csharp
  199. // You can use `var` for these cases:
  200. var direction = new Vector2(1, 0);
  201. var value = (int)speed;
  202. var text = "Some value";
  203. for (var i = 0; i < 10; i++)
  204. {
  205. }
  206. // But not for these:
  207. var value = GetValue();
  208. var velocity = direction * 1.5;
  209. // It's generally a better idea to use explicit typing for numeric values, especially with
  210. // the existence of the `real_t` alias in Godot, which can either be double or float
  211. // depending on the build configuration.
  212. var value = 1.5;
  213. Other considerations
  214. --------------------
  215. * Use explicit access modifiers.
  216. * Use properties instead of non-private fields.
  217. * Use modifiers in this order:
  218. ``public``/``protected``/``private``/``internal``/``virtual``/``override``/``abstract``/``new``/``static``/``readonly``.
  219. * Avoid using fully-qualified names or ``this.`` prefix for members when it's not necessary.
  220. * Remove unused ``using`` statements and unnecessary parentheses.
  221. * Consider omitting the default initial value for a type.
  222. * Consider using null-conditional operators or type initializers to make the code more compact.
  223. * Use safe cast when there is a possibility of the value being a different type, and use direct cast otherwise.