Search

Aug 12, 2008

Difference between internal and protected internal

Hi All,

Generally what we assume that internal means the variable that can only accessed within the assembly [which is the collection of namespace and classes].

But there is slide different meaning when we add protected to an internal member. What is that? The difference is... if you created a member which is protected internal then you can get it outside the assembly, but condition that you derive that class. Its protected so if you derive that class then in child class you can access the protected internal member.

We can check it out with example. Lets have a look at the classes which are in same assembly.

namespace Understand
{
public class C : UnderstandInternal.Class1
{
public C()
{
base.intInternalProtected(); // can call anything
base.intInternal();
}
}
}


namespace UnderstandInternal
{
public class Class1
{
internal int intInternal() { return 1; }
internal protected int intInternalProtected() { return 3; }
}


public class Class3
{
Class1 c = new Class1();
public Class3()
{
c.intInternalProtected(); // can call anything
c.intInternal();
}
}
}




You can see there is no problem in accessing the variable, its working fine, now we will do same thing in different assembly. Lets look at the following classes.








namespace TestConsole
{
class InternalTest : Class1
{
public InternalTest()
{
base.intInternalProtected(); //your can use here
base.intInternal(); //Error: 'UnderstandInternal.Class1' does not contain a definition for 'intInternal'

}
}

class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.intInternalProtected(); //Error: 'UnderstandInternal.Class1.intInternalProtected()' is inaccessible due to its protection level
c.intInternal(); //Error: 'UnderstandInternal.Class1' does not contain a definition for 'intInternal' and no extension method 'intInternal'
}
}
}

No comments: