C# Coding Conventions, The Better Way of Writing Your Code in Unity
"If you want your code to be easy to write, make it easy to read" - Robert C.Martin, author of Clean Code and Agile Software Development
Let’s talk about the C# naming conventions. Honestly, the thing that I just recently found out and did not realize before. Anyways, C# is typically written in camelCase
or PascalCase
conventions.
camelCase
camelCase
is when the first letter of the variable is lowercase and any proceeding words within the variable have the first letter in capital letters:
targetPosition
aimDirection
turnSpeed
PascalCase
PascalCase
is just like camelCase
except the first letter is capitalized:
CameraController
PoolingManager
UnityEngine
Ok, when should we use them neatly when programming in Unity? Well, let’s take a look at this typical script in Unity.
We will notice that the class name is in PascalCase
case. That means classes in C# are typically written using PascalCase
, we will also notice that Start
and Update
functions are also capitalized. So we can say methods are written using PascalCase
as well.
Next, Lets’s focus on the ExampleFunction
We can see the class type of the parameter (ExampleClass
)is remain PascalCase
, but the parameter ( FirstParameter
)itself is camelCase
as well as the local variable (exampleVariable
).
If a member variable has the public or protected access type (ExampleMember1
& ExampleMember2
), it is typically using PascalCase
. However, private member variables (_exampleMember3
)are denoted by an underscore and the camelCased
.
Static variables (ExampleStaticVariable
) are always written at the top of the class and in PascalCase
.
Interface declaration prefixes a capital I in PascalCase
convention and Enums are also written using PascalCase
.
Short notes
Codes that use PascalCase
convention:
- ClassNames
- Methods & Functions
- PublicMemberVariables
- ProtectedMemberVariables
- IInterfaces
- Enums
Codes that use camelCased
convention:
- _privateMemberVariables
- methodVariables & functionVariables
- parameters & arguments