c_sharp_style_guide.rst 10 KB

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