SOF User
SOF User

Reputation: 7840

Protecting Base class object in C#

How

 public class BaseAppConstants
    {
        public const string StLiveIdCookieName = "XYZ";
    }


public class AppConstants : BaseAppConstants
{


}

How can I make changes so user can not direct access base class they can only use like this AppConstants.StLiveIdCookieName;

Upvotes: 0

Views: 152

Answers (3)

Grant Thomas
Grant Thomas

Reputation: 45058

You should either

  • A) move the constant to the level at which is it supposed to be used (i.e. declare it in AppConstants and remove it from BaseAppConstants) or,

  • B) use a different modifier to make it inaccessible and provide an accessor in the other class (i.e. use protected in BaseAppConstants and reimplement in AppConstants with something like public const string StLiveIdCookieName = BaseAppConstants.StLiveIdCookieName - but this kind of defies the usage of constants).

Upvotes: 3

Nahum
Nahum

Reputation: 7197

use protected modifier seee :

http://msdn.microsoft.com/en-us/library/wxh6fsc7(v=vs.71).aspx

and for deteiled explanation

http://msdn.microsoft.com/en-us/library/ba0a1yw2(v=vs.71).aspx

Upvotes: 1

Mattias Josefsson
Mattias Josefsson

Reputation: 1197

If you set the property in the base class to protected it will only be usable in derived classes.

public class BaseAppConstants
{
    protected const string StLiveIdCookieName = "XYZ";
}

Read more about protected here.

Upvotes: 1

Related Questions