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

Amit Ghosh
Amit Ghosh
8,943 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
194,931 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
194,931 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
8,943 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
194,931 Points

See the comment added to my answer.

Steven Parker
Steven Parker
194,931 Points

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