简体   繁体   中英

Should I use private fields in my C# class or public Properties are good enough?

as my question said I'm confused in case where should I use private fields or not..

Here is my Person class for example:

I know it's useful to use private fields when I want to get FullName quickly.. Actually that's only example where I'm adding addition code in some of my getters, so I would like to avoid private fields, so I might start using public properties because anyway in the background private field will be created?

 private string _firstName;
 private string _lastName;

 public string FullName
 {
    get { return _firstName + _lastName; }
 }

Anyway, could I do something like this, remove private fields - > add only public properties ? I guess there is no issue about this code below.. ?

 public string FirstName { get; set; }
 public string LastName  { get; set; }

 public string FullName
 {
   get { return FirstName + LastName; }
 }

Should I prefer example 2? I mean is there any problems if I stay with example 2? Because I want my classes to look cleaner without private fields :)

The answer here will really depend on whether you want the first/last name to be on the public API. If you do: 2 is ideal for your typing convenience. At runtime, thanks to JIT magic, 1 and 2 will be largely indistinguishable (except for the accessibility concern), so you might as well go with the most convenient and expressive form, which is usually: 2.

Even 1 could use private automatically implemented properties if you so wish , although it is pretty rare to see that in reality - most code either uses public properties or private fields, depending on the intent; public fields are anecdotally rare, as are private properties.

It might also make sense to have the first and last names public but read-only, ie

public string FirstName { get; }
public string LastName  { get; }

public string FullName => FirstName + LastName;

or public but only writable inside the type:

public string FirstName { get; private set; }
public string LastName  { get; private set; }

public string FullName => FirstName + LastName;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM