1

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.

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

3 Answers3

4

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.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
  • Sometimes I don't understand people logic at all, like in this question http://stackoverflow.com/questions/2070661/how-do-i-have-to-change-this-xml-string-so-that-xdocument-parse-reads-it-in/2070783#2070783 – Restuta Dec 19 '11 at 05:22
  • @Restuta You actually appear to have gotten a pretty detailed explanation for the down vote there. – Andrew Barber Dec 19 '11 at 06:46
1

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.

qw20012
  • 89
  • 3
1

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.

Community
  • 1
  • 1
Restuta
  • 5,855
  • 33
  • 44