Samantha J T Star
Samantha J T Star

Reputation: 32808

How should I set up my private variables when I move them into a base class?

I have the following code in all of my controllers:

public class PackagesController : BaseController
{
    private IAccountService _account;
    private IDataSourceService _dataSource;
    private IPackageService _package;
    private IProductService _product;
    private IContentService _content;
    private ISequenceService _sequence;

They all inherit from BaseController. I'm a bit confused about the difference between public, private and protected. I am thinking I could move these into BaseController. If I did this then should I use private, protected or is there some other modifier.

Upvotes: 1

Views: 129

Answers (3)

Restuta
Restuta

Reputation: 5903

It seems that you should use protected after moving this fields to your BaseController.

Private means field is private for the type it's declared on. -- You will be able to use this fields only inside BaseController after you'll move them.

Protected means field is ok to use in all derived types as well, but not from outside. -- You will be able to use this fields inside BaseController and all derived ones after you'll move them.

Public means it can be used from everywhere. -- You will be able to use this fields from everywhere after you'll move them.

You can get more from MSDN and this SO question.

Upvotes: 1

qw20012
qw20012

Reputation: 89

After you move these variables from PackagesController to BaseController, if they are just used in BaseController, then they should be private, if they will be used in both PackagesController & BaseController, they should be protected. I don't seggust you the use 'public' for variables.

Upvotes: 1

Andrew Barber
Andrew Barber

Reputation: 40150

You would use Protected if you wanted the derived classes to have access. Private would prevent even the derived classes from accessing, which is not what you want. Public would let any code access them, which is not needed here, as you typically do not need access to Controller members from outside.

Upvotes: 4

Related Questions