Why protected internal class cannot derive? - c#

Scope of the protected internal is same assembly, or by any derived class in another assembly.Then Why protected internal class cannot derive?
Sample code:
protected internal class AbsClass
{
int m = 50;
public int am = 5;
public void nonAbsfn()
{
Console.WriteLine(m + am);
}
}
class TestAbstract : AbsClass
{
}

A class can only be protected internal if it is an inner class.
Otherwise, a class can only be public or internal.
To fix your compilation error, make the class either public or internal. The error you are getting has nothing to do with the derived class TestAbstract.

According to the MSDN documentation:
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
So you should be able to do it. Can you post some of your code?

Related

C#: Protected method in base class; unable to access using derived class object from another class [duplicate]

This question already has answers here:
is inaccessible due to its protection level
(9 answers)
Closed 5 years ago.
Should protected members of a base class be accessible to a class which inherits from base class?
I'm trying to access protected method of base class using an object of derived class from another class, but I get this error message
the base class method is inaccessible due to protection level
What am I doing wrong?
Program.cs
class Program
{
static void Main(string[] args)
{
DerivedClass dc = new DerivedClass();
dc.DisplayValue();
}
}
BaseClass.cs
class BaseClass
{
private int value = 3;
protected void DisplayValue()
{
Console.WriteLine(this.value);
}
}
DerivedClass.cs
class DerivedClass : BaseClass{}
The code within DerivedClass has access to protected members of BaseClass, but only via an expression of type DerivedClass or a subtype.
Your Main function is outside the Derived Class and that's why you are getting exception.
From section 3.5.3 of the C# 5 specification (emphasis mine):
When a protected instance member is accessed outside the program text
of the class in which it is declared, and when a protected internal
instance member is accessed outside the program text of the program in
which it is declared, the access must take place within a class
declaration that derives from the class in which it is declared.
Furthermore, the access is required to take place through an instance
of that derived class type or a class type constructed from it.
You can change you code to this for example to use protected function of the base class
public class Program
{
public static void Main(string[] args)
{
DerivedClass dc = new DerivedClass();
dc.Display();
}
}
public class BaseClass
{
private int value = 3;
protected void DisplayValue()
{
Console.WriteLine(this.value);
}
}
public class DerivedClass : BaseClass
{
public void Display()
{
DisplayValue();
}
}
Protected members are indeed visible from derived classes. But in your example you don't access DisplayValue from a derived class. You access it from Program, which does not derive from BaseClass. You need to make that member public.

Understanding Access specifiers on Classes in C#

First of all let me start by saying that I do understand access specifiers I just don't see the point of using them in classes. It makes sense on methods to limit their scope but on classes, why would you want a private class, isn't it the purpose of classes to be able to reuse them?
What is the purpose of access specifiers when declaring a class in C#? When would you use them?
Thanks
Well, let's say that you want a class to be only accessed inside her own assembly:
internal class Test
Let's say that you have two classes, one inside the other (nested classes):
protected internal class TestA
{
private TestB _testB;
private class TestB
{
}
public TestA()
{
_testB = new TestB();
}
}
The TestB class can be only accessed inside methods/properties/contructors inside TestA or inside herself.
The same applies to the protected modifier.
// Note
If you don't specify the access modifier, by default it will be private, so on my example the following line:
private TestB _testB;
is equal to
TestB _testB;
And the same applies to the class.
Special Modifier
Then, there is the protected internal which joins both modifiers so you can only access that class inside the same assembly OR from a class which is derived by this one even if it isn't in the same assembly. Example:
Assembly 1:
public class TestA : TestB
{
public TestB GetBase()
{
return (TestB)this;
}
public int GetA1()
{
return this.a1;
}
}
protected internal class TestB
{
public int a1 = 0;
}
Program
TestA _testA = new TestA(); // OK
TestB _testB = new TestB(); // ERROR
int debugA = new TestA().a1 // ERROR
int debugB = new TestA().GetA1(); // OK
TestB testB_ = new TestA().GetBase(); // ERROR
Source
Link (Access Modifiers)
Internal
The type or member can be accessed by any code in the same assembly,
but not from another assembly.
Private
The type or member can be accessed only by code in the same class or
struct.
Protected
The type or member can be accessed only by code in the same class or
struct, or in a class that is derived from that class.
Public
The type or member can be accessed by any other code in the same
assembly or another assembly that references it.
I will give you an example of an internal class. Imagine I have some DLL. Form this DLL I want to expose only a single class called A. This class A however, should have access to other classes inside DLL - thus I will make all other classes inside DLL internal. Hence, from the DLL you can only use class A, while A can still access other classes inside DLL - you however, can't.
The greatest benefit of using access specifiers is when someone else is using your classes. By clearly specifying, what should and what should not be touched within your objects, you can protect your object internal mechanism and integrity from being misused or damaged.
With bigger classes, if you made everything public, you would also make it harder for the user of your code to work with IntelliSense, which is something that is very handy when you deal with unknown libraries.
I have created one application to understand Access Specifiers.
It will be more easy to understand it with code instead of Theory.
I have added my notes in code, for better guidance.
namespace ConsoleApplication1
{
//A normal public class which contains all different types of access-modifier classes in the assembly named 'ConsoleApplication1'
public class Base
{
public class PublicBase
{
public static void fn_PublicBase()
{
Console.WriteLine("fn_PublicBase");
}
}
private class PrivateBase
{
public static void fn_PrivateBase()
{
Console.WriteLine("fn_PrivateBase");
}
}
protected class ProtectedBase
{
public static void fn_ProtectedBase()
{
Console.WriteLine("fn_ProtectedBase");
}
}
internal class InternalBase
{
public static void fn_InternalBase()
{
Console.WriteLine("fn_InternalBase");
}
}
protected internal class ProInternalBase
{
public static void fn_ProInternalBase()
{
Console.WriteLine("fn_ProInternalBase");
}
}
//TIP 1:This class is inside the same class 'Base' so everything is accessible from above.Hurray!!
class Base_Inside
{
public static void fn_Base_Inside()
{
//All methods are easily accessible.Does not consider a modified indeed.
PublicBase.fn_PublicBase();
PrivateBase.fn_PrivateBase();
ProtectedBase.fn_ProtectedBase();
InternalBase.fn_InternalBase();
ProInternalBase.fn_ProInternalBase();
}
}
}
//Different class but inside the same assembly named 'ConsoleApplication1'
public class Base_Sibling : Base
{
//TIP 2:This class is NOT in same class 'Base' but in the same assembly so only protected is NOT accessible rest all are accessible.
public void fn_Base_Sibling()
{
PublicBase.fn_PublicBase();
//PrivateBase.fn_PrivateBase(); //ERROR:Accesibility of 'protected'
ProtectedBase.fn_ProtectedBase(); //protected is accessible because Base_Sibling inherit class 'Base'. you can not access it via Base.ProtectedBase
InternalBase.fn_InternalBase();
ProInternalBase.fn_ProInternalBase();
}
}
}
Now to Understand difference between internal, protected internal,
I Have added one for project named with Assembly_1 in same
solution.
I have inherited Base class of ConsoleApplication1 to Derived class of Assembly_1.
namespace Assembly_1
{
//TIP:if it does not inherit class 'ConsoleApplication1.Base' then we can not access any thing beacuse this is different assembly.
//TIP:only INTERNAL is NOT accessible , rest all are accessible from first assembly if it inherits class 'Soul'
public class Derived : ConsoleApplication1.Base
{
public class PublicDerived
{
public static void fn_PublicDerived()
{
PublicBase.fn_PublicBase(); //YES, becuase this is 'public'
//PrivateBase.fn_PrivateBase(); //No, becuase this is 'private'
ProtectedBase.fn_ProtectedBase(); //YES, becuase this is 'protected'
//InternalBase.fn_InternalBase(); //No, becuase this is 'internal'
ProInternalBase.fn_ProInternalBase(); //YES, becuase this is 'protected internal'
}
}
}
}
- Update answer 2019 -
Hi You can find accessibility via below table

How to define "anonymous namespace" in C#?

In C++, in order to define a symbol that is only accessible within the same file, we say
namespace
{
class my_private_class
{ ... }
}
But can I do the same thing in C#? Or do I have to say
namespace __DO_NOT_USE_OUT_OF_.xxx.cs__
{
public MyPrivateClass
{ ... }
}
using __DO_NOT_USE_OUT_OF_.xxx.cs__;
(assuming this is in a file called xxx.cs)?
The later, of cause, will depend on the other programmer regards it or not.
There's no anonymous namespaces in C#, but you can exploit static classes:
namespace MyNamespace // <- Just a namespace
{
// Anonymous Namespace emulation:
// static class can't have instances and can't be inherited,
// it's abstract and sealed
internal static class InternalClass // or public static class
{
// private class, it's visible within InternalClass only
class my_private_class
{ ... }
}
}
There is no such thing in C#, we have something called access modifiers which manage the visibility of types.
The usage is against a class or method, such as:
internal class MyType
{
}
Or
protected void MyMethod()
{
}
You will have to pick the one that applies to your scenario, here are the details:
public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private
The type or member can be accessed only by code in the same class or struct.
protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

Protected member visible for user

It will be my first question here so please be lenient.
How is this possible:
//there is a Form1 class which has a TableAdapter member generated by designer...
partial class Form1
{
private void InitializeComponent()
{
this.SomeTableTableAdapter = new SomeDatabaseDataSetTableAdapters.SomeTableTableAdapter();
}
private SomeDatabaseDataSetTableAdapters.SomeTableTableAdapter SomeTableTableAdapter;
}
//here is this TableAdapter class
//It has PROTECTED member called "Adapter"
public partial class SomeTableTableAdapter : global::System.ComponentModel.Component
{
protected internal global::System.Data.SqlClient.SqlDataAdapter Adapter
{
}
}
//and in the constructor of Form1 class I can do something like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.SomeTableTableAdapter.Adapter.InsertCommand.CommandText = #"INSERT INTO (...)";
}
}
How come I get access to protected member since Form1 do not inherit from SomeTableTableAdapter?
protected internal means protected OR internal. Access is allowed either from derived classes or from the containing assembly.
Access Modifiers (C# Programming Guide):
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
The Adapter property is declared as protected internal, which means it is accessible to derived classes (protected) and to classes in the same assembly (internal). Since Form1 is in the same assembly as SomeTableTableAdapter, they can access each other's internal members.

How do I specify a method that can be accessed only from derived classes of the same assembly?

Is there any way in C# to specify a method that can be accessed only from derived classes of the same assembly without using internal access modifier?
Thanks.
You have to specify both internal as well as protected.
Give the scope of the class as internal
and method scope as protected
Internal class Myclass
{
Protected void MyMethod()
{
//Do something
}
}
Read about C# Protected Internal
protected A protected member is accessible within its class and by
derived classes.
internal Internal types or members are accessible only within
files in the same assembly.
protected internal Access is limited to the current assembly or
types derived from the containing
class.
* protected internal is the only access modifiers combination allowed
for a member or a type.
So you need to use internal key word after all:
protected internal memberName(){ ... };
I believe you can do something like:
public class OriginalClass { ... }
internal class DerivedClass: OriginalClass
{
protected void MemberName() { ... }
}
This way, only internal classes can see the DerivedClass and only internal derived classes can see the portected members inside it.
And also, you still able to access the OriginalClass from everywhere.
Ok! I imagine the situation where you would like to have more flexible control of what assembly class is from, and what class is derived from, than with 'internal' keyword. For example if you wish to check that the object is from th-a-at assembly and derives from one of the-e-e-ese classes.
You can do it through Assembly.GetAssembly() method of the type
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getassembly.aspx
And here is the way to check if object is derived one from another.
Check if a class is derived from a generic class
So you can check all you need.
Then you can implement something like:
public static bool CheckTypeIsCorrect(Type t)
{
if(t.GetAssembly().FullName != AssemblyYouNeed) return false;
if(!(check anything you want in the class)) return false;
return true;
}
...
public void YourMethod(object value)
{
if(!CheckTypeIsCorrect(typeof(value)))
throw ArgumentException("Type of the object is not correct");
...
}
Make the function Access modifier as Protected in your Base Class. Like below
protected void YourFunctionName()
{
//This will be accessible in your derived class only.
}
A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.
Below is an example from MSDN
namespace SameAssembly
{
public class A
{
protected void abc()
{
}
}
private class B : A
{
void F()
{
A a = new A();
B b = new B();
a.abc(); // Error
b.abc(); // OK
}
}
}

Categories