Reputation: 10153
I have three classes which have many common properties, so I generated a base class from which they inherit:
public class CommonConfig
{
public TimeSpan Period1 { get; private set; }
public TimeSpan Period2 { get; private set; }
public TimeSpan Period3 { get; private set; }
};
public class Config1 : CommonConfig
{
public long count1 {get; private set; }
}
public class Config2 : CommonConfig
{
public long count2 {get; private set; }
}
I am not sure that I want to make CommonConfig
to be public
. Is it possible to keep it private
but still make something that allows usage like below.
Config1 c1;
TimeSpan ts1 = c1.Period1;
Upvotes: 0
Views: 60
Reputation: 4487
If your aim is to prevent usage of the class CommonConfig
directly, you could mark the class CommonConfig
as abstract
and also the properties within it (as required).
That way, though the class would be visible but the only way to use it would be via Config1
or Config2
.
See this for more details.
Upvotes: 1
Reputation: 62265
No you can not, as to be able to access to the property of that class, you need to specify it public
, and you can not specify private
a class which properties are public
.
Config1 c1;
TimeSpan ts1 = c1.Period1; // THIS PROPERTY HS TO BE PUBLIC
and if you
//MISMATCH BETWEEN CLASS AND ITS PROPERTIES ACCESS MODIFIERS
private class CommonConfig {
public TimeSpan Period1 { get; private set; }
public TimeSpan Period2 { get; private set; }
public TimeSpan Period3 { get; private set; }
}
and even more, you will get compiler error:
Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal
As defining a class on the "top" level (on level of the namespace) you have to declare it public
. If you want to hide it, you have to declare that class inside another class.
Upvotes: 1
Reputation: 146
How about
public class CommonConfig
{
public TimeSpan Period1 {get; protected set;}
{
You could also make the whole attribute protected if needed...
Upvotes: 0
Reputation: 342
No You can not make it as private. you can not access private class with public property. you must specify Public class
Upvotes: 1
Reputation: 20764
You cannot make a class private
, internal
is the most restrictive possible modifier for a non nested class.
Also you cannot have the access for descendant classes less restrictive than the parent class, so you have to stick with public
for CommonConfig
.
Upvotes: 1