shavit shavit - 1 month ago 9
C# Question

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?

Answer

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;
Comments