си шарп стиль кода
C# Coding Conventions
Coding conventions serve the following purposes:
Naming conventions
There are several naming conventions to consider when writing C# code.
In 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.
Pascal case
When naming public members of types, such as fields, properties, events, methods, and local functions, use pascal casing.
When writing positional records, use pascal casing for parameters as they’re the public properties of the record.
For more information on positional records, see Positional syntax for property definition.
Camel case
When editing C# code that follows these naming conventions in an IDE that supports statement completion, typing _ will show all of the object-scoped members.
When writing method parameters, use camel casing.
For more information on C# naming conventions, see C# Coding Style.
Additional naming conventions
Examples that don’t include using directives, use namespace qualifications. If you know that a namespace is imported by default in a project, you don’t have to fully qualify the names from that namespace. Qualified names can be broken after a dot (.) if they are too long for a single line, as shown in the following example.
You don’t have to change the names of objects that were created by using the Visual Studio designer tools to make them fit other guidelines.
Layout conventions
Good layout uses formatting to emphasize the structure of your code and to make the code easier to read. Microsoft examples and samples conform to the following conventions:
Use the default Code Editor settings (smart indenting, four-character indents, tabs saved as spaces). For more information, see Options, Text Editor, C#, Formatting.
Write only one statement per line.
Write only one declaration per line.
If continuation lines are not indented automatically, indent them one tab stop (four spaces).
Add at least one blank line between method definitions and property definitions.
Use parentheses to make clauses in an expression apparent, as shown in the following code.
Commenting conventions
Place the comment on a separate line, not at the end of a line of code.
Begin comment text with an uppercase letter.
End comment text with a period.
Insert one space between the comment delimiter (//) and the comment text, as shown in the following example.
Don’t create formatted blocks of asterisks around comments.
Ensure all public members have the necessary XML comments providing appropriate descriptions about their behavior.
Language guidelines
The following sections describe practices that the C# team follows to prepare code examples and samples.
String data type
Use string interpolation to concatenate short strings, as shown in the following code.
To append strings in loops, especially when you’re working with large amounts of text, use a StringBuilder object.
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.
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.
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.
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.
Don’t use implicit typing to determine the type of the loop variable in foreach loops.
The following example uses explicit typing in a foreach statement.
Be careful not to accidentally change a type of an element of the iterable collection. For example, it is easy to switch from System.Linq.IQueryable to System.Collections.IEnumerable in a foreach statement, which changes the execution of a query.
Unsigned data types
Arrays
If you specify an array size, you have to initialize the elements one at a time.
Delegates
Use Func<> and Action<> instead of defining delegate types. In a class, define the delegate method.
Call the method using the signature defined by the Func<> or Action<> delegate.
If you create instances of a delegate type, use the concise syntax. In a class, define the delegate type and a method that has a matching signature.
Create an instance of the delegate type and call it. The following declaration shows the condensed syntax.
The following declaration uses the full syntax.
Use a try-catch statement for most exception handling.
Simplify 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.
You can do the same thing with a using statement.
In C# 8 and later versions, use the new using syntax that doesn’t require braces:
&& and || operators
To avoid exceptions and increase performance by skipping unnecessary comparisons, use && instead of & and || instead of | when you perform comparisons, as shown in the following example.
If the divisor is 0, the second clause in the if statement would cause a run-time error. But the && operator short-circuits when the first expression is false. That is, it doesn’t evaluate the second expression. The & operator would evaluate both, resulting in a run-time error when divisor is 0.
new operator
Use 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.
The preceding declarations are equivalent to the following declaration.
Use object initializers to simplify object creation, as shown in the following example.
The following example sets the same properties as the preceding example but doesn’t use initializers.
Event handling
If you’re defining an event handler that you don’t need to remove later, use a lambda expression.
The lambda expression shortens the following traditional definition.
Static members
Call 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.
LINQ queries
Use meaningful names for query variables. The following example uses seattleCustomers for customers who are located in Seattle.
Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal casing.
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.
Use implicit typing in the declaration of query variables and range variables.
Align query clauses under the from clause, as shown in the previous examples.
Use where clauses before other query clauses to ensure that later query clauses operate on the reduced, filtered set of data.
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.
Параметры правил стиля кода
Определяя параметры стиля кода в файле EditorConfig, вы создаете конфигурацию, на основе которой анализаторы стиля кода будут проверять ваш код. Файл EditorConfig — это файл конфигурации для таких анализаторов.
Параметры стиля кода также можно задать в диалоговом окне параметров текстового редактора Visual Studio. Эти параметры применяются только для пользователя и только при редактировании в Visual Studio. Они не учитываются во время сборки и в других IDE. Кроме того, если открываемые в Visual Studio проекты или решения содержат файл EditorConfig, то приоритет отдается параметрам из этого файла EditorConfig.
Различают следующие подкатегории правил стиля кода:
Каждая из этих подкатегорий определяет собственный синтаксис для указания параметров. Дополнительные сведения об этих правилах и параметрах для них см. в справочнике по правилам стиля кода.
Пример файла EditorConfig
Чтобы помочь вам приступить к работе, ниже приведен пример файла EDITCONFIG с параметрами по умолчанию.
В Visual Studio 2019 и более поздних версиях (для Windows) вы можете создать этот файл и сохранить его в проекте в разделе Сервис > Параметры > Текстовый редактор > [C# или Basic] > Стиль кода > Общее. Затем нажмите кнопку Создание EDITORCONFIG-файла из параметров. Дополнительные сведения см. в статье о параметрах стиля кода.
C#: требования и рекомендации по написанию кода
Я немного поизучал имеющиеся предложения из этих источников:
submain.com/blog/FreeCVBNETCodingGuidelinesEbookDownload.aspx
idesign.net/idesign/DesktopDefault.aspx
и скомпилировал черновик который описывает самые базовые правила оформления кода написанного на C#.
Предлагаю:
— обсудить этот черновик;
— внести в него все необходимые изменения;
— утвердить как стандарт написания C# кода на Хабре.
Более того, предлагаю создать документ, который можно было бы предложить как рекомендации habrahabr comunity для всех других программистов C#.
Под катом вы найдете текст черновика. Предлагаю всем желающим обсудить его и подвергнуть надлежащей правке.
1. Требования
1.1 Pascal casing
namespace SampleNamespace
<
enum SampleEnum
<
FirstValue,
SecondValue
>
struct SampleStruct
<
public int FirstField;
public int SecondField;
>
interface ISampleInterface
<
void SampleMethod();
>
public class SampleClass: SampleInterface
<
const int SampleConstValue = 0xffffff;
readonly int SampleReadonlyField;
public int SampleProperty
<
get ;
set ;
>
public int SamplePublicField;
SampleClass()
<
SampleReadonlyField = 1;
>
delegate void SampleDelegate();
event SampleDelegate SampleEvent;
1.2 Camel casing
protected int sampleProtectedField;
1.3 Суффиксы и префиксы
public class SampleException: System. Exception
<
public SampleException()
<
>
>
interface ISample
<
void SampleMethod();
>
1.4 Аббревиатуры
2. Рекомендации
2.1 Именование методов
В частном случае, для методов, которые возвращают значение, используйте в паре глагол-объект для глагола «Get», а для объекта – описание возвращаемого значения.
2.2 Переменные, поля и свойства
• При именовании переменных избегайте использования сокращенных вариантов вроде I и t, используйте index и temp. Не используйте венгерскую нотацию или используйте ее только для закрытых членов. Не сокращайте слова, используйте number, а не num.
• Рекомендуется для имен элементов управления указывать префиксы, описывающие тип элемента. Например: txtSample, lblSample, cmdSample или btnSample. Эта же рекомендация распространяется на локальные переменные сложных типов: ThisIsLongTypeName tltnSample = new ThisIsLongTypeName();
• не используйте публичных или защищенных полей, вместо этого используйте свойства;
• используйте автоматические свойства;
• всегда указывайте модификатор доступа private, даже если разрешено его опускать;
• всегда инициализируйте переменные, даже когда существует автоматическая инициализация.
2.3 Дополнительные рекомендации
2.4 Объем кода
• избегайте файлов с более чем 500 строками кода;
• избегайте методов с более чем 200 строками кода;
• избегайте методов с более чем 5 аргументами, используйте структуры для передачи большого числа параметров;
• одна строка кода не должна иметь длину более 120 символов.
3. Спорные моменты для обсуждения
3.1 Закрытые поля
private int m_SamplePrivateField;
private int mSamplePrivateField;
private int _samplePrivateField;
Си шарп стиль кода
The Official raywenderlich.com 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.
This style guide is based on C# and Unity conventions.
On the whole, naming should follow C# standards.
AVOID:
PREFER:
All non-static fields are written camelCase. Per Unity convention, this includes public fields as well.
AVOID:
PREFER:
Static fields are the exception and should be written in PascalCase:
All properties are written in PascalCase. For example:
Parameters are written in camelCase.
AVOID:
PREFER:
Single character values are to be avoided except for temporary looping variables.
Actions are written in PascalCase. For example:
In code, acronyms should be treated as words. For example:
AVOID:
PREFER:
Access Level Modifiers
Access level modifiers should be explicitly defined for classes, methods and member variables.
Prefer single declaration per line.
AVOID:
PREFER:
Exactly one class per source file, although inner classes are encouraged where scoping appropriate.
All interfaces should be prefaced with the letter I.
AVOID:
PREFER:
Spacing is especially important in raywenderlich.com code, as code needs to be easily readable as part of the tutorial.
Indentation should be done using spaces — never tabs.
Indentation for blocks uses 4 spaces for optimal readability:
AVOID:
PREFER:
Indentation for line wraps should use 4 spaces (not the default 8):
AVOID:
PREFER:
Lines should be no longer than 100 characters long.
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.
All braces get their own line as it is a C# convention:
AVOID:
PREFER:
Conditional statements are always required to be enclosed with braces, irrespective of the number of lines required.
AVOID:
PREFER:
Switch-statements come with default case by default (heh). If the default case is never reached, be sure to remove it.
AVOID:
PREFER:
Use US English spelling.
AVOID:
PREFER:
The exception here is MonoBehaviour as that’s what the class is actually called.
The following copyright statement should be included at the top of every source file:
Smiley faces are a very prominent style feature of the raywenderlich.com site! It is very 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.
Краткий обзор языка C#
C# — это объектно- и компонентно-ориентированный _ язык программирования. C# предоставляет языковые конструкции для непосредственной поддержки такой концепции работы. Благодаря этому C# подходит для создания и применения программных компонентов. С момента создания язык C# обогатился функциями для поддержки новых рабочих нагрузок и современными рекомендациями по разработке ПО. C# — это _ объектно-ориентированный язык. Вы определяете типы и их поведение.
Исходный код, написанный на языке C# компилируется в промежуточный язык (IL), который соответствует спецификациям CLI. Код на языке IL и ресурсы, в том числе растровые изображения и строки, сохраняются в сборке, обычно с расширением .dll. Сборка содержит манифест с информацией о типах, версии, языке и региональных параметрах для этой сборки.
При выполнении программы C# сборка загружается в среду CLR. Среда CLR выполняет JIT-компиляцию из кода на языке IL в инструкции машинного языка. Среда CLR также выполняет другие операции, например, автоматическую сборку мусора, обработку исключений и управление ресурсами. Код, выполняемый в среде CLR, иногда называется управляемым кодом. «Неуправляемый код» преобразуется в машинный язык, предназначенный для конкретной платформы.
Здравствуй, мир
Для первого знакомства с языком программирования традиционно используется программа «Hello, World». Вот ее пример на C#:
Типы и переменные
Тип определяет структуру и поведение любых данных в C#. Объявление типа может включать его члены, базовый тип, интерфейсы, которые он реализует, и операции, разрешенные для этого типа. Переменная — это метка, которая ссылается на экземпляр определенного типа.
В C# существуют две разновидности типов: ссылочные типы и типы значений. Переменные типа значений содержат непосредственно данные, а в переменных ссылочных типов хранятся ссылки на нужные данные, которые именуются объектами. Две переменные ссылочного типа могут ссылаться на один и тот же объект, поэтому может случиться так, что операции над одной переменной затронут объект, на который ссылается другая переменная. Каждая переменная типа значения имеет собственную копию данных, и операции над одной переменной не могут затрагивать другую (за исключением переменных параметров ref и out ).
Типы значений в C# делятся на простые типы, типы перечислений, типы структур, типы, допускающие значение NULL, и типы значений кортежей. Ссылочные типы в C# подразделяются на типы классов, типы интерфейсов, типы массивов и типы делегатов.
Далее представлены общие сведения о системе типов в C#.
В C# существует несколько типов переменных, в том числе поля, элементы массива, локальные переменные и параметры. Переменные представляют собой места хранения, и каждая переменная имеет тип, который определяет допустимые значения для хранения в этой переменной. Примеры представлены ниже.
Структура программы
В качестве небольшого примера рассмотрим сборку, содержащую следующий код:
Сборка полностью описывает сама себя и содержит весь код и метаданные, поэтому в C# не используются директивы #include и файлы заголовков. Чтобы использовать в программе C# открытые типы и члены, содержащиеся в определенной сборке, вам достаточно указать ссылку на эту сборку при компиляции программы. Например, эта программа использует класс Acme.Collections.Stack из сборки acme.dll :
Для компиляции программы вам потребуется создать ссылку на сборку, содержащую класс стека, определенный в примере выше.
Программы C# можно хранить в нескольких исходных файлах. При компиляции программы C# все исходные файлы обрабатываются вместе, при этом они могут свободно ссылаться друг на друга. По сути, это аналогично тому, как если бы все исходные файлы были объединены в один большой файл перед обработкой. В C# никогда не используются опережающие объявления, так как порядок объявления, за редким исключением, не играет никакой роли. В C# нет требований объявлять только один открытый тип в одном исходном файле, а также имя исходного файла не обязано совпадать с типом, объявляемом в этом файле.
Такие организационные блоки описываются в других статьях этого обзора.