Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# protected field to private, add property--why?

In Visual Studio 2008 Team System, I just ran Code Analysis (from the Analyze menu) on one of my C# projects. One of the warnings produced was the following:

Microsoft.Design : Because field 'Connection._domain' is visible outside of its declaring type, change its accessibility to private and add a property, with the same accessibility as the field has currently, to provide access to it.

It's referring to the following field:

public abstract class Connection
{
    protected string _domain;
}

I don't understand the reasoning behind the suggestion. This is what I think it wants me to do:

public abstract class Connection
{
    private string _domain;
    protected string Domain { get { return _domain; } set { _domain = value; } }
}

Two questions:

  1. Did I understand correctly what the suggestion wants me to do, code-wise?
  2. Why does it want me to do this?
like image 528
Sarah Vessels Avatar asked Nov 09 '09 20:11

Sarah Vessels


1 Answers

Yes, I think you understood correctly - although in later versions of C#, there's a more concise way to write it:

public string Domain { get; set; }

Why? It's all about encapsulation. If you do as it suggests, you can later change the definition of the Domain property without affecting any calling code that uses that property. Since your class is public, and might conceivably be called by code that you didn't write, that's potentially quite important.

like image 87
Gary McGill Avatar answered Sep 30 '22 01:09

Gary McGill