Is there any C# naming convention for a variable used in a property?

Viewed 61529

Let's say, we have a variable, which we want named Fubar

Let's say that Fubar is a String!

That means, we would define Fubar as so:

public string Fubar;

Now, let's say we want Fubar to have a getter and setter (or in other words, become a C# property)!

private string Fubar;
public string Fubar_gs
{
    get
    {
        //Some fancy logic
        return Fubar;
    }
    set
    {
        //Some more fancy logic
        Fubar = value;
    }
}

Well great! That is all fine and dandy, EXCEPT, what if I wanted the PROPERTY to be named Fubar, not the original variable?

Well obviously, I would just rename both variables. But the problem is, what would be the best name for the original variable?

Is there a naming convention for this situation?

12 Answers

Well, the Framework Design Guidelines document states the following:

Names of Fields The field-naming guidelines apply to static public and protected fields. Internal and private fields are not covered by guidelines, and public or protected instance fields are not allowed by the member design guidelines.

āœ“ DO use PascalCasing in field names.

āœ“ DO name fields using a noun, noun phrase, or adjective.

X DO NOT use a prefix for field names.

For example, do not use "g_" or "s_" to indicate static fields.

So, for private fields, there is no official recommendation. However, if you use VS 2017 quick action "Convert to full property" on a property, this happens:

VS 2017 quick action "Convert to full property"

So it seems like it is safe to assume that prefixing private fields with an underscore is somewhat standard.

I thing, one name is better:

public string Fubar { get; private set; }

I see a ton of outdated answers (and non-standard ways representing C#6), so this one's for 2020:

// "fubar" works, too, but "_" prevents CaSe typo mistakes
private string _fubar;
public string Fubar
{
    get => _fubar;
    set => _fubar = value;
}

// Read-only can just use lambda to skip all those shenannigans
public string ReadOnlyFoo => "This is read-only!";

While most developers follow Microsoft's guideline, as game developers, we follow Unity's style as (one of the script source code here):

static protected Material s_DefaultText = null;
protected bool m_DisableFontTextureRebuiltCallback = false;
public TextGenerator cachedTextGenerator { ... }
Related