Question

I have a project in C# where there are two namespaces defined in seperate files where one is the subset of the other:

namespace RSSTimerJob

namespace RSSTimerJob.Features.RSSFilter

I have a static class called Toolbox which belongs to the 1st namespace. Now when I try to call the protected static variables of the Toolbox class from a custom class in the 2nd namespace, I get an error saying its inaccessible due to its protection level.

Why does it give me this error. Since the 2nd namespace is a subset of the 1st, doesnt that mean that making the variable protected should allow the 2nd namespace's class to see it?

Setting the variables to public of course, makes this error go away but I am just curious :)

Was it helpful?

Solution

protected is not the keyword you want to use.

internal allows access to members of classes to other classes in the same assembly.

In C#, protected allows access to base members to classes that derive from that base. You might be thinking of Java, where protected is slightly different, in that it grants access to subclasses plus classes within the same package. To get roughly that same behavior in C#, you would use the combination protected internal, which is inclusive of protected and internal, granting access for derived classes as well as access for classes in the same assembly.

OTHER TIPS

protected means that the thing is available to the class itself and derived classes.

I wouldn't go berserk with namespaces though. They're useful if you've got lot of things to put in them and these things are different enough. Here's some guidelines on namespace best-practices.

"protected" means that that member can be accessed from the same class, or from derived classes. But that doesn't allow other members of the same namespace to access that member.

What you are looking for is probably "internal", that means the member can be accessed by code in the same assembly.

By the way you can add more members to the same namespace from a different assembly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top