Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fields and properties Best Practice in C# [closed]

Tags:

c#

c#-3.0

Dear all, which one is the best practice using C# and why?
1.

private string name;

public string Name
{
  get { return name; }
  set { name = value; }
}

2.

public string Name { get; set; }

3.

protected string name;
public string Name
{
  get { return name; }
  set { name = value; }
}

4. Please add ...

like image 331
yayan Avatar asked Nov 28 '22 04:11

yayan


2 Answers

Snippets 1 and 2 are both fine. The second is simply a more convenient way of writing the first for when you don't need access to the underlying field.

Snippet 3, however, should generally be avoided (unless you have some specific reason for needing it), as fields should almost always be private. If you need to provide a different way of setting the field for descendant classes (which is unlikely), then you could use methods or another property.

Remember that a protected member is essentially just a slightly more restricted public member, since it can be accessed by client code as long as it's in a descendant class. This means that client code can become tied directly into the implementation of the class rather than its interface, which is a bad thing!

like image 51
Will Vousden Avatar answered Dec 05 '22 17:12

Will Vousden


Start with the second snippet, i.e.

public string Name { get; set; }

Change it to the form of the first snippet when you need to add validation, or do some logic when the value is set.

I'd avoid the last option, as it would allow an overriding class to directly access the backing field which ties you to a specific implementation (it also means that your lovely validation can be bypassed)

like image 45
Rowland Shaw Avatar answered Dec 05 '22 18:12

Rowland Shaw