shavit
shavit

Reputation: 1063

Is there any reason to use very simple properties over fields?

I currently have this code written:

public class General
{
    /// <summary>
    /// Private variables.
    /// </summary>
    private const float fVersion = 1.3f;
    private static bool bMonitoring = false;

    /// <summary>
    /// Retrieves the current version of the application.
    /// </summary>
    public static float Version
    {
        get
        {
            return fVersion;
        }
    }

    /// <summary>
    /// Are we monitoring performance?
    /// </summary>
    public static bool Monitoring
    {
        get
        {
            return bMonitoring;
        }

        set
        {
            bMonitoring = value;
        }
    }
}

In case I check for General.bMonitoring or General.Version often (maybe.. over 100 times a second!) and really care about performance: is it good practice to leave my class written like that, or should I simply delete these properties and make the fields public?

Upvotes: 1

Views: 111

Answers (2)

Roman Marusyk
Roman Marusyk

Reputation: 24569

In this case if you aren't going to add some logic to the getter or setter then I would use static fields. Performance will be the same.

But if later you need extra logic when you set ot get values then it preffer to use properties because it allows for versioning and it gives you Encapsulation according to OOP principles. Don't care about performance

For Monitoring property you can use Auto-Implemented Property like

public static bool Monitoring { get; set; }

but in this case you need to implement a static constructor (thanks to @Mafii)

    static General()
    {
        Monitoring  = false;
    }

or if you use C# 6.0 then just:

public static bool Monitoring { get; set; } = false;

Upvotes: 2

Niyoko
Niyoko

Reputation: 7662

Don't worry about performance. Property access is (and should be) very fast and compiler may inline them.

Property is preferred over field not because of performance, but because encapsulation and it will really helps when later you need for example checking or make property computed.

More by Jon Skeet http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx

Upvotes: 1

Related Questions