c# - Inconsistent accessibility: base class is less accessible than child class -
i reading book "c# 4.0 in nutshell" joseph albabari , ben albabari. there find topic restrictions on access modifiers. page 91, topic "restrictions on access modifiers".
quoting book.
the compiler prevents inconsistent use of access modifiers. example, sub- class can less accessible base class, not more
so says base class should equally or more accessible subclass. if base class internal subclass should either private or internal. if base class private , sub class public compile time error generated. while trying in visual studio found strange behavior.
try 1: base private , sub class private (works, right behavior) works if both internal, public.
private class { } private class b : { } // works try 2: base private , sub class public or internal (this fails, right behavior)
private class { } public class b : { } // error try 3 : base internal , sub public (this works, should fail. base less accessible sub class
internal class { } public class b : { } // works, why now question why try 3 didn't failed? sub class public , more accessible base class internal. book says should fail. visual studio compiled successfully. should work or not?
edit:
i created new console project in vs. in program.cs added code. here complete code of program.cs file.
using system; using system.collections.generic; using system.linq; using system.text; using system.io; namespace consoleapplication { class program { internal class { } public class b : { } // error static void main() { } } }
you placing nested classes within internal class.
for example, given:
class program { static void main(string[] args) { } internal class { } public class b : { } } it will compile because internal modifier of wrapping class makes public modifier on class b moot. rather, type b's accessibility limited wrapped class program -- accessibility domain internal well.
if update be:
class program { static void main(string[] args) { } } internal class { } public class b : { } it throw inconsistent visibility compiler error. or if redefine program public instead of internal throw error. in case, b's accessibility domain public , no longer limited program's internal accessibility domain.
from c# specification 3.5.2 accessibility domains:
the accessibility domain of nested member m declared in type t within program p defined follows (noting m may possibly type):
if declared accessibility of m public, accessibility domain of m accessibility domain of t.
and msdn's description of accessibility domain:
if member nested within type, accessibility domain determined both accessibility level of member , accessibility domain of containing type.
if wrapping type program internal, nested type b being public have accessibility match program, treated internal , no compiler error thrown.
Comments
Post a Comment