Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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
229,744 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
229,744 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.

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
229,744 Points

See the comment added to my answer.

Thanks Steven

Steven Parker
Steven Parker
229,744 Points

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