Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: naming rules for protected members fields

In our .NET software component we use the following naming convention. When a customer use our DLL from VB.NET, the compiler cannot distinguish distance member field from the Distance property. What workaround do you recommend?

Thanks.

public class Dimension : Text
{
    private string _textPrefix;

    protected double distance;

    /// <summary>
    /// Gets the real measured distance.
    /// </summary>
    public double Distance
    {
        get { return Math.Abs(distance); }
    }
}
like image 772
abenci Avatar asked Jul 08 '16 12:07

abenci


1 Answers

You should not use fields that are protected, for the reason that versioning and access cannot be guarded. See the Field Design guidelines. Change your field to a property, which will also force you to change to name (as you cannot have two properties with the same name). Or, if possible, make the protected field private.

To make setting your property accessible only to the inheriting classes, use a protected setter:

public class Dimension : Text
{
    private string _textPrefix;

    private double _absoluteDistance;

    /// <summary>
    /// Gets the real measured distance.
    /// </summary>
    public double Distance
    {
        get { return _absoluteDistance  }
        protected set { _absoluteDistance = Math.Abs(distance); }
    }
}

Although that does cause divergence between get and set, as functionality is not the same. Perhaps a separate protected method would be better in this case:

public class Dimension : Text
{
    private string _textPrefix;

    /// <summary>
    /// Gets the real measured distance.
    /// </summary>
    public double Distance { get; private set; }

    protected void SetAbsoluteDistance(double distance)
    {
        Distance = Math.Abs(distance);
    }
}
like image 151
Wicher Visser Avatar answered Oct 11 '22 01:10

Wicher Visser