2

I've read the naming convention in https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions.

However, I couldn't find the answer for this example below:

public class A
{
    private int _b;
    
    // Should I use "_" + camel case to name this member:
    private string _c => _b.ToString();
    
    // Or should I use pascal case to name this member:
    private string C => b.ToString();
}
  1. Should the member _c or C be called "private property" with a getter method or "private calculated field"? why?

  2. If we want to use a member private internally with an expression body(=>) similar to this example. What is the naming convention for it?

Bowen
  • 381
  • 6
  • 11
  • 1
    _"However, it didn't mention this case:"_ - well **yes it did**. All three members in your code are _fields_ and so the following guideline applies _["Use camel casing ("camelCasing") when naming private or internal fields, and prefix them with _"](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions)_. The fact that you are using `=>` is incidental. –  Dec 23 '21 at 06:48
  • Opinion, not an answer. I'd go with `C` (i.e., PascalCase) since it's a read-only property. It's the property-ness that makes it PascalCase, it's public/private-ness doesn't matter. @MickyD: the `=>` certainly matters, it makes `C` a read-only property, not a field – Flydog57 Dec 23 '21 at 07:07

1 Answers1

1

As a common usage style in C#, fields start with a lowercase letter, properties start with a capital letter. Generally, fields begin with the _ character. If the data member is a field, it would be more appropriate to call it _c, and if it's a property, it would be called C.

Properties show fields. Fields are privately defined within a class and must be accessed via the get and set properties. Properties provide a level of abstraction that allows you to modify fields without affecting the external path accessed by clients using your class.

In this example, you don't need to define a field or property if you want clients to always use the _b variable as a string:

public class A
{
    private int _b;

    public string GetBAsString()
    {
        return _b.ToString();
    }
}

References
Sercan
  • 4,739
  • 3
  • 17
  • 36
  • I have updated my question, what if I need a private member and with an expression body and its output is taking existing filed into account. Should this member be called a "property" or "field". I know almost always properties are public, but can't it be private? – Bowen Dec 23 '21 at 07:50
  • A property is _field-like_ in appearance and usage, but runs code for a _getter_ and/or a _setter_. It doesn't matter if it's private or public. Your `C` is a private, read-only property (the getter calls `_b.ToString()`, there is no setter) – Flydog57 Dec 23 '21 at 16:38