Coder Social home page Coder Social logo

c-sharp-style-guide's Introduction

Table of Contents

The Official Kodeco C# Style Guide

This style guide is different from others you may find, because the focus is centered on readability for print and the web. We created this style guide to keep the code in our tutorials consistent.

Our overarching goals are conciseness, readability and simplicity. Also, this guide is written to keep Unity in mind.

Inspiration

This style guide is based on C# and Unity conventions.

Nomenclature

On the whole, naming should follow C# standards.

Namespaces

Namespaces are all PascalCase, multiple words concatenated together, without hyphens ( - ) or underscores ( _ ). The exception to this rule are acronyms like GUI or HUD, which can be uppercase:

AVOID:

com.kodeco.fpsgame.hud.healthbar

PREFER:

Kodeco.FPSGame.HUD.Healthbar

Classes & Interfaces

Classes and interfaces are written in PascalCase. For example RadialSlider.

Methods

Methods are written in PascalCase. For example DoSomething().

Fields

All non-static fields are written camelCase. Per Unity convention, this includes public fields as well.

For example:

public class MyClass 
{
    public int publicField;
    int packagePrivate;
    private int myPrivate;
    protected int myProtected;
}

AVOID:

private int _myPrivateVariable

PREFER:

private int myPrivateVariable

Static fields are the exception and should be written in PascalCase:

public static int TheAnswer = 42;

Properties

All properties are written in PascalCase. For example:

public int PageNumber 
{
    get { return pageNumber; }
    set { pageNumber = value; }
}

Parameters

Parameters are written in camelCase.

AVOID:

void DoSomething(Vector3 Location)

PREFER:

void DoSomething(Vector3 location)

Single character values are to be avoided except for temporary looping variables.

Actions

Actions are written in PascalCase. For example:

public event Action<int> ValueChanged;

Misc

In code, acronyms should be treated as words. For example:

AVOID:

XMLHTTPRequest
String URL
findPostByID

PREFER:

XmlHttpRequest
String url
findPostById

Declarations

Access Level Modifiers

Access level modifiers should be explicitly defined for classes, methods and member variables.

Fields & Variables

Prefer single declaration per line.

AVOID:

string username, twitterHandle;

PREFER:

string username;
string twitterHandle;

Classes

Exactly one class per source file, although inner classes are encouraged where scoping appropriate.

Interfaces

All interfaces should be prefaced with the letter I.

AVOID:

RadialSlider

PREFER:

IRadialSlider

Spacing

Spacing is especially important in kodeco.com code, as code needs to be easily readable as part of the tutorial.

Indentation

Indentation should be done using spaces โ€” never tabs.

Blocks

Indentation for blocks uses 4 spaces for optimal readability:

AVOID:

for (int i = 0; i < 10; i++) 
{
  Debug.Log("index=" + i);
}

PREFER:

for (int i = 0; i < 10; i++) 
{
    Debug.Log("index=" + i);
}

Line Wraps

Indentation for line wraps should use 4 spaces (not the default 8):

AVOID:

CoolUiWidget widget =
        someIncrediblyLongExpression(that, reallyWouldNotFit, on, aSingle, line);

PREFER:

CoolUiWidget widget =
    someIncrediblyLongExpression(that, reallyWouldNotFit, on, aSingle, line);

Line Length

Lines should be no longer than 100 characters long.

Vertical Spacing

There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods.

Brace Style

All braces get their own line as it is a C# convention:

AVOID:

class MyClass {
    void DoSomething() {
        if (someTest) {
          // ...
        } else {
          // ...
        }
    }
}

PREFER:

class MyClass
{
    void DoSomething()
    {
        if (someTest)
        {
          // ...
        }
        else
        {
          // ...
        }
    }
}

Conditional statements are always required to be enclosed with braces, irrespective of the number of lines required.

AVOID:

if (someTest)
    doSomething();  

if (someTest) doSomethingElse();

PREFER:

if (someTest) 
{
    DoSomething();
}  

if (someTest)
{
    DoSomethingElse();
}

Switch Statements

Switch-statements come with default case by default (heh). If the default case is never reached, be sure to remove it.

AVOID:

switch (variable) 
{
    case 1:
        break;
    case 2:
        break;
    default:
        break;
}

PREFER:

switch (variable) 
{
    case 1:
        break;
    case 2:
        break;
}

Language

Use US English spelling.

AVOID:

string colour = "red";

PREFER:

string color = "red";

The exception here is MonoBehaviour as that's what the class is actually called.

Copyright Statement

The following copyright statement should be included at the top of every source file:

/*
 * Copyright (c) 2023 Kodeco Inc.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, 
 * distribute, sublicense, create a derivative work, and/or sell copies of the 
 * Software in any work that is designed, intended, or marketed for pedagogical or 
 * instructional purposes related to programming, coding, application development, 
 * or information technology.  Permission for such use, copying, modification,
 * merger, publication, distribution, sublicensing, creation of derivative works, 
 * or sale is expressly withheld.
 *    
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

In this repository, copy the ScripTemplates folder into your own Unity Assets folder. This way the header above will be included in new scripts.

NOTE: You may need to close and reopen Unity in order for it to start picking up the template.

Smiley Face

Smiley faces are prominent style feature of the kodeco.com site! It's important to have the correct smile signifying the immense amount of happiness and excitement for the coding topic. The closing square bracket ] is used because it represents the largest smile able to be captured using ASCII art. A closing parenthesis (":)") creates a half-hearted smile, and thus is not preferred.

AVOID:

:)

PREFER:

:]

NOTE: Do not use smileys in your scripts.

Credits

This style guide is a collaborative effort from the most stylish kodeco.com team members:

c-sharp-style-guide's People

Contributors

3ncy avatar blackdragonbe avatar dover8 avatar jellodiil avatar pabu avatar rwenderlich avatar sammyd avatar shogan avatar vegetarianzombie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

c-sharp-style-guide's Issues

Use of variable name "packagePrivate"

In the fields casing guide it shows:

int packagePrivate;

In C#, when you leave off the access modifier, I believe members default to private, unlike java, which defaults to package private.

Also, being a bit nitpicky, but I think "package private" in c#, would be internal, but I don't think the term package is used. I think it would be assembly, or project. Unless package is a unity thing.

No recommendation given on when to use delegate declarations

The guide makes recommendations about delegate style, but not when to use them. I feel like it suggests that they should be used, when, for the examples given, Action is a simpler choice. (A couple Unity forum users and I had a brief discussion five years ago which might give some insight.)

I can think of two cases where I would use a named delegate.

  1. Clarity for curried methods. Probably outside the scope of this guide.
  2. When the delegate takes at least one parameter. This should go in the style guide if the raywenderlich.com style is to use named parameters. I believe everyone should, but realize that's contentious.
delegate void DoMeaningfulThings(int count, string name);

static void FunctionWithSameSignature(int count, string name) {}

static void UnimportantFunction() 
{            
    // Unimportant values.
    var count = 11, name = "Jane Doremi";
    
    DoMeaningfulThings doMeaningfulThings = (count, name) => 
    {
        // meaningful things are done here
    };
    
    // Why you'd use a custom delegate instead of an Action<int, string>:
    // parameter names from the delegate are usable.
    doMeaningfulThings(count: count, name: name);
    
    // Compiles, but lacks clarity.
    doMeaningfulThings(count, name);
    
    // Compiles.
    Action<int, string> action = FunctionWithSameSignature;
    action(count, name);
    
    // Neither compiles. Actions can't carry parameter names. 
    action(count: count, name: name);
    action = doMeaningfulThings;            
}

If you don't want to take on named parameters at this point, I would suggest a "Prefer Action and Func" guideline, or an argument against using them in all cases.

Inconsistent example of "acronyms should be treated as words".

There is a section that says "In code, acronyms should be treated as words", with an example of "Bad: XMLHTTPRequest, Good: XmlHttpRequest". However, early in the document, there is an example of acronyms not being treated as words. "Namespaces are all PascalCase, multiple words concatenated together, without hypens ( - ) or underscores ( _ ):" and "Good: RayWenderlich.FPSGame.HUD.Healthbar".

I would either like to see it explicit that namespaces (and other things? if so what other things) don't count as code, or it should be consistent as "RayWenderlich.FpsGame.Hud.Healthbar" (this doesn't seem right to me, most everyone uses upper case letters for their acronyms in namespaces, including Unity).

Thank you!

Events: "methods" confusing; "On" breaks convention

The guide currently includes:

Prefix event methods with the prefix On.

event methods is not a standard term in C#, and so I was confused by what it was referring to.

I believe the examples suggest that the word method should be left off of that sentence.

However, this suggestion breaks convention:

BAD: public static event CloseCallback Close;
GOOD: public static event CloseCallback OnClose;

It even goes against the specific MSDN example "use Close instead of OnClose".

There is a convention for when to use the On prefix. It is not for an event itself, but for a protected (or occasionally private) method that calls the actual event, which has the same name, aside from the On prefix.

Should an example be made to show when to use On, or is that too heavy for this guide? I didn't yet find an example of Microsoft officially going into when to use On, so it might be able to be left off for now. However, I think a link to that SO post, or one of the several similar ones, would be educational.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.