P
P
Pavel2019-03-22 06:08:50
C++ / C#
Pavel, 2019-03-22 06:08:50

What is the preferred style/decoration of C# source code?

Came to C# from C/C++. I would like to understand how to format C# code correctly. In addition to the "low-level" readability of the code itself, it is interesting how to improve the "high-level" readability, file navigation, especially partial classes. In C/C++ I have used .h as Table Of Contents.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Pavlov, 2019-03-22
@HEKOT

https://docs.microsoft.com/en-us/dotnet/csharp/pro...
To separate program parts into logical blocks, #region is used, for example, a separate region for fields and properties, for public and private methods, for constructors and event handlers. I often make a region to indicate the implementation of an interface.
Regions can be within regions. Regions can be inside a class and inside method code.
It is good practice for class members (at least public ones) to specify descriptions with ///.
For example:

/// <summary>
/// Работа с данными
/// </summary>
class MyClass : IMyInterface, INotifyPropertyChanged, ICloneable, IDisposable
{
    #region поля

    private readonly Timer _timer;

    #endregion 

    #region ctor

    /// <summary>
    /// Конструктор по умолчанию для работы с данными
    /// </summary>
    public MyClass()
        : this(100500)
    {
    }
    
    /// <summary>
    /// Конструктор для работы с данными
    /// </summary>
    /// <param name="data">Данные</param>
    /// <param name="interval">Интервал таймера</param>
    public MyClass(int data, int interval = 10000)
    {
        _innerData = data;
        _timer = new Timer(interval);
    }

    #endregion

    #region IMyInterface

    private int _innerData;

    /// <summary>
    /// Данные
    /// </summary>
    public int Data => _innerData > 0 ? _innerData : 0;

    /// <summary>
    /// Выполнить работу
    /// </summary>
    public void DoWork()
    {
            
    }

    #endregion

    #region IDisposable

    public void Dispose()
    {
        _timer.Close();
    }

    #endregion

    #region ICloneable

    object ICloneable.Clone()
    {
        return Clone();
    }

    /// <summary>
    /// Клонировать
    /// </summary>
    public MyClass Clone()
    {
        return (MyClass)MemberwiseClone();
    }

    #endregion

    #region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

M
Maxim, 2019-03-22
@arantar

Stylecop Analyzers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question