Giter Site home page Giter Site logo

codestyles's Introduction

C# Style Guide

Table of Contents
  1. Pascal case
  2. Camel case
  3. String data type
  4. Implicitly typed local variables
  5. MySQL Migrations
  6. Data model conventions



Naming conventions

Pascal case

public class DataService
{
}
public record PhysicalAddress(
    string Street,
    string City,
    string StateOrProvince,
    string ZipCode);
public struct ValueCoordinate
{
}

When naming an interface, use pascal casing in addition to prefixing the name with an I. This clearly indicates to consumers that it's an interface.

public interface IWorkerQueue
{
}

When naming public members of types, such as fields, properties, events, methods, and local functions, use pascal casing.

public class ExampleEvents
{
    // A public field, these should be used sparingly
    public bool IsValid;

    // An init-only property
    public IWorkerQueue WorkerQueue { get; init; }

    // An event
    public event Action EventProcessing;

    // Method
    public void StartEventProcessing()
    {
        // Local function
        static int CountQueueItems() => WorkerQueue.Count;
        // ...
    }
}

When writing positional records, use pascal casing for parameters as they're the public properties of the record.

public record PhysicalAddress(
    string Street,
    string City,
    string StateOrProvince,
    string ZipCode);



Camel case

Use camel casing ("camelCasing") when naming private or internal fields, and prefix them with _.

public class DataService
{
    private IWorkerQueue _workerQueue;
}

When working with static fields that are private or internal, use the s_ prefix and for thread static use t_.

public class DataService
{
    private static IWorkerQueue s_workerQueue;

    [ThreadStatic]
    private static TimeSpan t_timeSpan;
}

When writing method parameters, use camel casing.

public T SomeMethod<T>(int someNumber, bool isValid)
{
}



String data type

Use string interpolation to concatenate short strings, as shown in the following code.

string displayName = $"{nameList[n].LastName}, {nameList[n].FirstName}";

To append strings in loops, especially when you're working with large amounts of text, use a StringBuilder object.

var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
var manyPhrases = new StringBuilder();
for (var i = 0; i < 10000; i++)
{
    manyPhrases.Append(phrase);
}
//Console.WriteLine("tra" + manyPhrases);



Implicitly typed local variables

Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.

var var1 = "This is clearly a string.";
var var2 = 27;

Don't use var when the type is not apparent from the right side of the assignment. Don't assume the type is clear from a method name. A variable type is considered clear if it's a new operator or an explicit cast.

int var3 = Convert.ToInt32(Console.ReadLine()); 
int var4 = ExampleClass.ResultSoFar();

Don't rely on the variable name to specify the type of the variable. It might not be correct. In the following example, the variable name inputInt is misleading. It's a string.

var inputInt = Console.ReadLine();
Console.WriteLine(inputInt);

Avoid the use of var in place of dynamic. Use dynamic when you want run-time type inference. For more information, see Using type dynamic (C# Programming Guide).

Use implicit typing to determine the type of the loop variable in for loops.

The following example uses implicit typing in a for statement.

var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
var manyPhrases = new StringBuilder();
for (var i = 0; i < 10000; i++)
{
    manyPhrases.Append(phrase);
}
//Console.WriteLine("tra" + manyPhrases);

Don't use implicit typing to determine the type of the loop variable in foreach loops. In most cases, the type of elements in the collection isn't immediately obvious. The collection's name shouldn't be solely relied upon for inferring the type of its elements.

The following example uses explicit typing in a foreach statement.

foreach (char ch in laugh)
{
    if (ch == 'h')
        Console.Write("H");
    else
        Console.Write(ch);
}
Console.WriteLine();



MySQL Migrations

Declare primary key, foreign keys and other properties in this order

In DBContext,

modelBuilder.Entity<Client>(entity =>
{
    entity.ToTable("clients")
        .HasKey(e => e.Id);

    entity.Property(e => e.Id)
        .HasColumnName("id");

    entity.Property(e => e.ClientAuthId)
        .HasColumnName("client_auth_id")
        .HasColumnType("varchar(124)");

    entity.Property(e => e.Name)
        .HasColumnName("name")
        .HasColumnType("varchar(124)");

    entity.Property(e => e.Status)
        .HasColumnName("status")
        .HasColumnType("enum('active','deactivated')")
        .HasDefaultValue("active");

    entity.Property(e => e.CreatedAt)
        .HasColumnName("created_at");

    entity.Property(e => e.UpdatedAt)
        .HasColumnName("updated_at");

    entity.HasIndex(e => new { e.ClientAuthId })
        .HasDatabaseName("clients_auth_id_index")
        .IsUnique();
});

Data model conventions

  • Add comments for each property
  • Declare primary key, foreign key and other properties in this order
  • Declare ? for nullable properties with datatypes of string and add = default!
public class ClientCallback
{
    /// <summary>
    /// Gets or sets the client callback id.
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// Gets or sets the client id.
    /// </summary>
    public int ClientId { get; set; }

    /// <summary>
    /// Gets or sets the callback type.
    /// </summary>
    public string Type { get; set; } = ClientCallbackConstants.CallbackType.Disbursement;

    /// <summary>
    /// Gets or sets the callback url.
    /// </summary>
    public string CallbackUrl { get; set; } = default!;

    public virtual Client Client { get; set; } = default!;
}

codestyles's People

Contributors

jillzyt avatar

Watchers

 avatar

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.