Jan 21 2006

Internal and Public Access Modifiers in C#

Category:Bil@l @ 16:47

I am working on a project, in which I have several Class Libraries. In one of the class libraries, I wanted to use an object that can be accessed only inside the class library. What I did is I created the class as:

internal class X
    // Class content

Among my class in this class library, I had two objects, one of the objects calls a method inside the other object, and passes to it a parameter of type X, which is an internal object. One thing to mention here that all methods inside those objects have public direcive.
I used to get this error message:

Error 9 Inconsistent accessibility: parameter type 'NameSpace.X' is less accessible than method 'NameSpace.Object1.Create(NameSpace.X)'

I relaized later after some debugging that, when you want to pass an object marked as internal between methods in seperate objects, those objects should also be marked internal and not something else.

You might say, how will be able to access those methods from outside the class library. Well, in my case, I needed to use those internal objects for internal processing inside those methods. So, if a class has a method that uses one of the internal objects to process X job and then returns a value that has a basic data type or a custom object (not marked internal), then all work fine. Example:

public class Y
    public static bool IsRegistered(string username)
        X _x = new X(username);
        bool result = IsValid(_x);

        return result;

As you can see, Y is a public class, and a method inside it is using the internal object and thus, that would be ok.

Hope that helps you.



Comments are closed