{"id":28317725,"url":"https://github.com/igece/coding-conventions","last_synced_at":"2025-06-24T15:32:09.340Z","repository":{"id":144136872,"uuid":"589908446","full_name":"igece/Coding-Conventions","owner":"igece","description":"A curated guide with coding conventions for C#.","archived":false,"fork":false,"pushed_at":"2023-01-17T08:20:58.000Z","size":6,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-01T14:18:35.317Z","etag":null,"topics":["coding-conventions","csharp","guide","guidelines"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/igece.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2023-01-17T08:19:44.000Z","updated_at":"2023-01-17T08:23:45.000Z","dependencies_parsed_at":null,"dependency_job_id":"4abd24c6-b2aa-463d-bd96-7544ae5ec269","html_url":"https://github.com/igece/Coding-Conventions","commit_stats":{"total_commits":2,"total_committers":1,"mean_commits":2.0,"dds":0.0,"last_synced_commit":"d89c8bd0899aca55d1d075f77dbf4bf135c31e37"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/igece/Coding-Conventions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/igece%2FCoding-Conventions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/igece%2FCoding-Conventions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/igece%2FCoding-Conventions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/igece%2FCoding-Conventions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/igece","download_url":"https://codeload.github.com/igece/Coding-Conventions/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/igece%2FCoding-Conventions/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261703117,"owners_count":23196899,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["coding-conventions","csharp","guide","guidelines"],"created_at":"2025-05-25T06:12:36.246Z","updated_at":"2025-06-24T15:32:09.327Z","avatar_url":"https://github.com/igece.png","language":null,"readme":"# C# Coding Conventions\n\nThe conventions observed in this document serve the following purposes:\n\n- They create a consistent look to the code, so that readers can focus on content, not layout.\n- They enable readers to understand the code more quickly by making assumptions based on previous experience.\n- They facilitate copying, changing, and maintaining the code.\n- They demonstrate C# best practices.\n\n# Naming conventions\n\nThere are several naming conventions to consider when writing C# code.\n\nIn the following examples, any of the guidance pertaining to elements marked public is also applicable when working with protected and protected internal elements, all of which are intended to be visible to external callers.\n\n## Pascal case\n\nUse pascal casing (\"PascalCasing\") when naming a `class`, `record`, or `struct`.\n\n``` c#\npublic class DataService\n{\n}\n```\n``` c#\npublic struct ValueCoordinate\n{\n}\n```\n\n\nWhen 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.\n\n``` c#\npublic interface IWorkerQueue\n{\n}\n```\n\nWhen naming public members of types, such as fields, properties, events, methods, and local functions, use pascal casing.\n\n``` c#\npublic class ExampleEvents\n{\n    // A public field, these should be used sparingly\n    public bool IsValid;\n\n    // An init-only property\n    public IWorkerQueue WorkerQueue { get; init; }\n\n    // An event\n    public event Action EventProcessing;\n\n    // Method\n    public void StartEventProcessing()\n    {\n        // Local function\n        static int CountQueueItems() =\u003e WorkerQueue.Count;\n        // ...\n    }\n}\n```\n\n## Camel case\n\nUse camel casing (\"camelCasing\") when naming private or internal fields, and prefix them with _.\n\n``` c#\npublic class DataService\n{\n    private IWorkerQueue _workerQueue;\n}\n```\n\nWhen writing method parameters, use camel casing.\n\n\n``` c#\npublic T SomeMethod\u003cT\u003e(int someNumber, bool isValid)\n{\n}\n```\n\n# Layout conventions\n\n- Good layout uses formatting to emphasize the structure of your code and to make theh code easier to read.\n\n- Use the default Code Editor settings (smart indenting, four-character indents, tabs saved as spaces). For more information, see Options, Text Editor, C#, Formatting.\n\n- Write only one statement per line.\n\n- Write only one declaration per line.\n\n- If continuation lines are not indented automatically, indent them one tab stop (four spaces).\n\n- Add at least one blank line between method definitions and property definitions.\n\n- Use parentheses to make clauses in an expression apparent, as shown in the following code.\n\n\n``` c#\nif ((val1 \u003e val2) \u0026\u0026 (val1 \u003e val3))\n{\n    // Take appropriate action.\n}\n```\n\n# Commenting conventions\n\n- Place the comment on a separate line, not at the end of a line of code.\n\n- Begin comment text with an uppercase letter.\n\n- End comment text with a period.\n\n- Insert one space between the comment delimiter (//) and the comment text, as shown in the following example.\n\n``` c#\n// The following declaration creates a query. It does not run\n// the query.\n```\n\n- Don't create formatted blocks of asterisks around comments.\n\n- Ensure all public members have the necessary XML comments providing appropriate descriptions about their behavior.\n\n# Language guidelines\n\nThe following sections describe practices that the C# team follows to prepare code examples and samples.\n\n## String data type\n\nUse string interpolation to concatenate short strings, as shown in the following code.\n\n``` c#\nstring displayName = $\"{nameList[n].LastName}, {nameList[n].FirstName}\";\n```\n\nTo append strings in loops, especially when you're working with large amounts of text, use a StringBuilder object.\n\n\n``` c#\nvar phrase = \"lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala\";\nvar manyPhrases = new StringBuilder();\nfor (var i = 0; i \u003c 10000; i++)\n{\n    manyPhrases.Append(phrase);\n}\n//Console.WriteLine(\"tra\" + manyPhrases);\n```\n\n## Implicitly typed local variables\n\n- 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.\n\n``` c#\nvar var1 = \"This is clearly a string.\";\nvar var2 = 27;\n```\n\n- 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.\n\n``` c#\nint var3 = Convert.ToInt32(Console.ReadLine()); \nint var4 = ExampleClass.ResultSoFar();\n```\n\n- 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.\n\n``` c#\nvar inputInt = Console.ReadLine();\nConsole.WriteLine(inputInt);\n```\n\n- 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).\n\n## Unsigned data types\n\nIn general, use `int` rather than unsigned types. The use of `int` is common throughout C#, and it is easier to interact with other libraries when you use `int`.\n\n## Arrays\n\nUse the concise syntax when you initialize arrays on the declaration line. In the following example, note that you can't use var instead of string[].\n\n``` c#\nstring[] vowels1 = { \"a\", \"e\", \"i\", \"o\", \"u\" };\n```\n\nIf you use explicit instantiation, you can use `var`.\n\n``` c#\nvar vowels2 = new string[] { \"a\", \"e\", \"i\", \"o\", \"u\" };\n```\n\nIf you specify an array size, you have to initialize the elements one at a time.\n\n``` c#\nvar vowels3 = new string[5];\nvowels3[0] = \"a\";\nvowels3[1] = \"e\";\n// And so on.\n```\n\n## Delegates\n\nUse `Func\u003c\u003e` and `Action\u003c\u003e` instead of defining delegate types. In a class, define the delegate method.\n\n``` c#\npublic static Action\u003cstring\u003e ActionExample1 = x =\u003e Console.WriteLine($\"x is: {x}\");\n\npublic static Action\u003cstring, string\u003e ActionExample2 = (x, y) =\u003e \n    Console.WriteLine($\"x is: {x}, y is {y}\");\n\npublic static Func\u003cstring, int\u003e FuncExample1 = x =\u003e Convert.ToInt32(x);\n\npublic static Func\u003cint, int, int\u003e FuncExample2 = (x, y) =\u003e x + y;\n```\n\nCall the method using the signature defined by the `Func\u003c\u003e` or `Action\u003c\u003e` delegate.\n\n``` c#\nActionExample1(\"string for x\");\n\nActionExample2(\"string for x\", \"string for y\");\n\nConsole.WriteLine($\"The value is {FuncExample1(\"1\")}\");\n\nConsole.WriteLine($\"The sum is {FuncExample2(1, 2)}\");\n```\n\n## `try-catch` and `using` statements in exception handling\n\nUse a try-catch statement for most exception handling.\n\n``` c#\nstatic string GetValueFromArray(string[] array, int index)\n{\n    try\n    {\n        return array[index];\n    }\n\n    catch (System.IndexOutOfRangeException ex)\n    {\n        Console.WriteLine(\"Index is out of range: {0}\", index);\n        throw;\n    }\n}\n```\n\nSimplify your code by using the C# `using` statement. If you have a `try-finally` statement in which the only code in the finally block is a call to the `Dispose` method, use a using statement instead.\n\nIn the following example, the `try-finally` statement only calls `Dispose` in the `finally` block.\n\n\n``` c#\nFont font1 = new Font(\"Arial\", 10.0f);\n\ntry\n{\n    byte charset = font1.GdiCharSet;\n}\n\nfinally\n{\n    if (font1 != null)\n    {\n        ((IDisposable)font1).Dispose();\n    }\n}\n```\n\nYou can do the same thing with a using statement.\n\n``` c#\nusing (Font font2 = new Font(\"Arial\", 10.0f))\n{\n    byte charset2 = font2.GdiCharSet;\n}\n```\n\n## `\u0026\u0026` and `||` operators\nTo avoid exceptions and increase performance by skipping unnecessary comparisons, use `\u0026\u0026` instead of `\u0026` and `||` instead of `|` when you perform comparisons, as shown in the following example.\n\n``` c#\nConsole.Write(\"Enter a dividend: \");\nint dividend = Convert.ToInt32(Console.ReadLine());\n\nConsole.Write(\"Enter a divisor: \");\nint divisor = Convert.ToInt32(Console.ReadLine());\n\nif ((divisor != 0) \u0026\u0026 (dividend / divisor \u003e 0))\n{\n    Console.WriteLine(\"Quotient: {0}\", dividend / divisor);\n}\n\nelse\n{\n    Console.WriteLine(\"Attempted division by 0 ends up here.\");\n}\n```\n\nIf the divisor is 0, the second clause in the if statement would cause a run-time error. But the `\u0026\u0026` operator short-circuits when the first expression is false. That is, it doesn't evaluate the second expression. The \u0026 operator would evaluate both, resulting in a run-time error when divisor is 0.\n\n## new operator\nUse one of the concise forms of object instantiation, as shown in the following declarations. The second example shows syntax that is available starting in C# 9.\n\n``` c#\nvar instance1 = new ExampleClass();\n```\n``` c#\nExampleClass instance2 = new();\n```\n\nThe preceding declarations are equivalent to the following declaration.\n\n``` c#\nExampleClass instance2 = new ExampleClass();\n```\n\n- Use object initializers to simplify object creation, as shown in the following example.\n\n``` c#\nvar instance3 = new ExampleClass { Name = \"Desktop\", ID = 37414,\n    Location = \"Redmond\", Age = 2.3 };\n```\n\nThe following example sets the same properties as the preceding example but doesn't use initializers.\n\n``` c#\nvar instance4 = new ExampleClass();\ninstance4.Name = \"Desktop\";\ninstance4.ID = 37414;\ninstance4.Location = \"Redmond\";\ninstance4.Age = 2.3;\n```\n\n## Event handling\n\nIf you're defining an event handler that you don't need to remove later, use a lambda expression.\n\n``` c#\npublic Form2()\n{\n    this.Click += (s, e) =\u003e\n        {\n            MessageBox.Show(\n                ((MouseEventArgs)e).Location.ToString());\n        };\n}\n```\n\nThe lambda expression shortens the following traditional definition.\n\n``` c#\npublic Form1()\n{\n    this.Click += new EventHandler(Form1_Click);\n}\n\nvoid Form1_Click(object sender, EventArgs e)\n{\n    MessageBox.Show(((MouseEventArgs)e).Location.ToString());\n}\n```\n\n## Static members\n\nCall static members by using the class name: ClassName.StaticMember. This practice makes code more readable by making static access clear. Don't qualify a static member defined in a base class with the name of a derived class. While that code compiles, the code readability is misleading, and the code may break in the future if you add a static member with the same name to the derived class.\n\n## LINQ queries\n\n- Use meaningful names for query variables. The following example uses seattleCustomers for customers who are located in Seattle.\n\n``` c#\nvar seattleCustomers = from customer in customers\n                       where customer.City == \"Seattle\"\n                       select customer.Name;\n```\n\n- Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal casing.\n\n``` c#\nvar localDistributors =\n    from customer in customers\n    join distributor in distributors on customer.City equals distributor.City\n    select new { Customer = customer, Distributor = distributor };\n```\n\n- Rename properties when the property names in the result would be ambiguous. For example, if your query returns a customer name and a distributor ID, instead of leaving them as Name and ID in the result, rename them to clarify that Name is the name of a customer, and ID is the ID of a distributor.\n\n``` c#\nvar localDistributors2 =\n    from customer in customers\n    join distributor in distributors on customer.City equals distributor.City\n    select new { CustomerName = customer.Name, DistributorID = distributor.ID };\n```\n\n- Use implicit typing in the declaration of query variables and range variables.\n\n``` c#\nvar seattleCustomers = from customer in customers\n                       where customer.City == \"Seattle\"\n                       select customer.Name;\n```\n\n- Align query clauses under the from clause, as shown in the previous examples.\n\n- Use where clauses before other query clauses to ensure that later query clauses operate on the reduced, filtered set of data.\n\n``` c#\nvar seattleCustomers2 = from customer in customers\n                        where customer.City == \"Seattle\"\n                        orderby customer.Name\n                        select customer;\n```\n\n- Use multiple from clauses instead of a join clause to access inner collections. For example, a collection of Student objects might each contain a collection of test scores. When the following query is executed, it returns each score that is over 90, along with the last name of the student who received the score.\n\n``` c#\nvar scoreQuery = from student in students\n                 from score in student.Scores\n                 where score \u003e 90\n                 select new { Last = student.LastName, score };\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Figece%2Fcoding-conventions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Figece%2Fcoding-conventions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Figece%2Fcoding-conventions/lists"}