Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# Entity Framework with ASP.NET MVC Data Access Design Patterns Using the Repository Pattern

Amit Ghosh
Amit Ghosh
9,314 Points

When to use a Field vs a Property

Is there a clear guideline when to use a field vs a property. In the examples of Repository pattern, I can get away with creating a private Context field in the base class controller and use that in derived class controllers and pass a copy to the repository class.

I want to understand when to use Context property over a field and what is the thought process of choosing one over the other.

Thanks, Amit.

3 Answers

Steven Parker
Steven Parker
220,415 Points

I would not expect that you could access a private field from a derived class! But fields should only be private, and properties should use when access is to be allowed outside of the class.

For other info about using fields vs. properties, see the MDN Design Guidelines for Field Design and Property Design.

Steven Parker
Steven Parker
220,415 Points

Your first example creates a field with protected access, this would not in accordance with the "best practice" recommendations. The second example would be the preferred implementation.

Amit Ghosh
Amit Ghosh
9,314 Points

Steven let me ask the question in a different manner.

While creating class hierarchy what is the preferred way to defining the attributes being used by the derived classes:

For ex:

Approach 1:

public abstract class BaseController: Controller
{
    protected Context _context = null;
    public BaseController()
    {
        _context = new Context();
    }

}

Approach 2:

public abstract class BaseController: Controller
{
    protected Context Context {get; set;};
    public BaseController()
    {
        Context = new Context();
    }

}

I have implemented the logic both ways and its produces expected results. So the question is when to use which one and why?

Is this what should be followed: fields should only be private, and properties should use when access is to be allowed outside of the class.

Steven Parker
Steven Parker
220,415 Points

See the comment added to my answer.

Steven Parker
Steven Parker
220,415 Points

Amit Ghosh — Glad to help. You can mark a question solved by choosing a "best answer".
And happy holidays!   :christma_tree: