Reputation: 679
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 :)
Upvotes: 1
Views: 966
Reputation: 1062580
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, i.e.
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;
Upvotes: 2