Unity Software Inc.

09/07/2022 | Press release | Distributed by Public on 09/07/2022 13:31

Clean up your code: How to create your own C# code style

Variables typically represent a state, so try to attribute clear and descriptive nouns for their names. You can then prefix booleans with a verbfor variables that must indicate a true or false value. Often they are the answer to a question such as, is the player running? Is the game over? Prefix them with a verb to clarify their meaning. This is often paired with a description or condition, e.g., isPlayerDead, isWalking, hasDamageMultiplier, etc.

Since methods perform actions, a good rule of thumb is to start their names with a verb and add context as needed, e.g., GetDirection, FindTarget, and so on, based on the return type. If the method has a bool return type, it can also be framed as a question.

Much like boolean variables themselves, prefix methods with a verb if they return a true-false condition This phrases them in the form of a question, e.g., IsGameOver, HasStartedTurn.

Several conventions exist for naming events and event handles. In our style guide, we name the event with a verb phrase,similar to a method. Choose a name that communicates the state change accurately.Use the present or past participle to indicate events "before" or "after." For instance, specify OpeningDoor for an event before opening a door and DoorOpened for an event afterward.

We also recommend that you don't abbreviate names. While saving a few characters can feel like a productivity gain in the short term, what is obvious to you now might not be in a year's time to another teammate. Your variable names should reveal their intent and be easy to pronounce. Single letter variables are fine for loops and math expressions, but otherwise, you should avoid abbreviations. Clarity is more important than any time saved from omitting a few vowels.

At the same time, use one variable declaration per line; it's less compact, but also less error prone and enhances readability. Avoid redundant names. If your class is called Player, you don't need to create member variables called PlayerScore or PlayerTarget. Trim them down to Score or Target.

In addition, avoid too many prefixes or special encoding.A practice highlighted in our guide is to prefix private member variables with an underscore (_) to differentiate them from local variables. Some style guides use prefixes for private member variables (m_), constants (k_), or static variables (s_), so the name reveals more about the variable.

However, it's good practice to prefix interface names with a capital "I" and follow this with an adjective that describes the functionality. You can even prefix the event raising method (in the subject) with "On": The subject that invokes the event usually does so from a method prefixed with "On," e.g., OnOpeningDoor or OnDoorOpened.